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

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

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


当前回答

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

});

其他回答

使用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();
});

非常简单。首先将值存储在变量中。然后将事件集的值更改为存储的变量,该变量包含的初始值

我有一个名字是映射的。那么我的代码将如下所示;

$("document").ready(function(){ 
    var mapping=$("select[name=mapping]").val();
    $("select[name=mapping]").change(function(){
        $("select[name=mapping]").val(mapping);
    });
});

输入为<select>元素:

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

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

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

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

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

这个javascript找到所有的'select'与'readonly'属性,然后把disabled在'options'除了selected(回发)

文档。querySelectorAll("select[readonly] > option:not([selected])")。forEach((el) => el。setAttribute("disabled", "disabled")); 不带readonly: <select> <选项> 1 > < /选项 <选项> 2 > < /选项 <选项> 3 < /选项> < /选择> < br > 带readonly: <select readonly="readonly"> <选项> 1 > < /选项 <选项> 2 > < /选项 <选项> 3 < /选项> < /选择>