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

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

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


当前回答

输入为<select>元素:

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

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

其他回答

这是最简单、最好的解决办法。 您将在您的选择上设置一个readolny属性,或任何其他属性,如data-readonly,并执行以下操作

$("select[readonly]").live("focus mousedown mouseup click",function(e){
    e.preventDefault();
    e.stopPropagation();
});

我用jquery解决了它:

      $("select.myselect").bind("focus", function(){
        if($(this).hasClass('readonly'))
        {
          $(this).blur();   
          return;
        }
      });

除了禁用不应该是可选的选项,我想实际上让他们从列表中消失,但仍然能够启用他们,我应该以后需要:

$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);

它会找到所有带有只读属性的select元素,然后找到那些未被选中的select元素中的所有选项,然后隐藏它们并禁用它们。

出于性能考虑,将jquery查询分为2是很重要的,因为jquery从右向左读取它们,代码如下:

$("select[readonly] option:not(:selected)")

将首先找到文档中所有未选中的选项,然后筛选那些在具有只读属性的选择内的选项。

下面是一个尝试使用自定义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="disabled",而不是选择本身