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

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

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


当前回答

什么我发现伟大的工作,与纯javascript(即:没有JQuery库要求),是改变innerHTML的<select>标记为所需的单个剩余值。

之前:

<select name='day' id='day'>
  <option>SUN</option>
  <option>MON</option>
  <option>TUE</option>
  <option>WED</option>
  <option>THU</option>
  <option>FRI</option>
  <option>SAT</option>
</select>

示例Javascript:

document.getElementById('day').innerHTML = '<option>FRI</option>';

后:

<select name='day' id='day'>
  <option>FRI</option>
</select>

这样,没有视觉效果的改变,这将POST/GET在<FORM>。

其他回答

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

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

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

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

输入为<select>元素:

input.querySelectorAll(':not([selected])').forEach(option => {
  option.disabled = true
})

这将保留数据中的选择(因为它没有被禁用),并且只有未被选中的选项是禁用的,因此是不可选的。 结果是一个不可更改的可读选择(=>只读)。

给select元素添加readOnly属性的另一种方法是使用css

你可以这样做:

$('#selection').css('pointer-events','none');

DEMO

下面是一个尝试使用自定义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);

});

还有一个更现代的选项(没有双关语的意思)是禁用选择元素的所有选项,除了选中的选项。

但是请注意,这是一个HTML 4.0特性 而ie 6 7 8 1似乎不符合这个。

http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html