根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。

唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。

什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?


当前回答

使用tabindex解决方案。适用于选择和文本输入。

简单地使用.disabled类。

CSS:

.disabled {
    pointer-events:none; /* No cursor */
    background-color: #eee; /* Gray background */
}

JS:

$(".disabled").attr("tabindex", "-1");

HTML:

<select class="disabled">
    <option value="0">0</option>
</select>

<input type="text" class="disabled" />

编辑:使用Internet Explorer,你还需要这个JS:

$(document).on("mousedown", ".disabled", function (e) {
    e.preventDefault();
});

其他回答

在一个选项中,你可以使用disabled="disabled",而不是选择本身

下面是一个尝试使用自定义jQuery函数来实现的功能(如这里所述):

$(function(){

 $.prototype.toggleDisable = function(flag) {
    // prepare some values
    var selectId = $(this).attr('id');
    var hiddenId = selectId + 'hidden';
    if (flag) {
      // disable the select - however this will not submit the value of the select
      // a new hidden form element will be created below to compensate for the 
      // non-submitted select value 
      $(this).attr('disabled', true);

      // gather attributes
      var selectVal = $(this).val();
      var selectName = $(this).attr('name');

      // creates a hidden form element to submit the value of the disabled select
      $(this).parents('form').append($('<input></input>').
        attr('type', 'hidden').
        attr('id', hiddenId).
        attr('name', selectName).
        val(selectVal) );
    } else {
      // remove the newly-created hidden form element
      $(this).parents('form').remove(hiddenId);
      // enable back the element
      $(this).removeAttr('disabled');
    }
  }

  // Usage
  // $('#some_select_element').toggleDisable(true);
  // $('#some_select_element').toggleDisable(false);

});

简单地说,在提交表单之前删除disabled属性。

    $('form').submit(function () {
        $("#Id_Unidade").attr("disabled", false);
    });

如果你禁用了一个表单字段,当表单被提交时,这将不会被发送。 所以如果你需要一个像disabled一样工作但发送值的readonly,可以这样做:

在元素的只读属性发生任何变化之后。

$('select.readonly option:not(:selected)').attr('disabled',true);

$('select:not([readonly]) option').removeAttr('disabled');

所以无论出于什么原因,这里提到的所有基于jquery的解决方案都不适合我。所以这里是一个纯javascript的解决方案,它也应该在做POST时保留所选的值。

setDropdownReadOnly('yourIdGoesHere',true/false)

函数setDropdownReadOnly(controlName, state) { var ddl = document.getElementById(controlName); For (i = 0;I < ddl.length;我+ +){ if (i == ddl.selectedIndex) ddl[我]。禁用= false; 其他的 ddl[我]。禁用=状态; } }