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

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

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


当前回答

如果您有一个应该是只读的选择标记,那么从逻辑上讲,您必须将选择框转换为单个“文本”字段。

我说逻辑是因为它就像: "我必须向用户显示一个值"

无论该值是否来自选择标记,都仍然是单个值且不能更改(只读)。

因此,从逻辑上讲,只有在第一次插入值时才使用选择标记。

然后,当你需要显示这个值时,你必须把它放在“文本字段只读”上。

如果多选项为只读,则变成一个值列表(所选值)

我使用“text”是因为一个只读标记不需要“type”属性。 干杯

其他回答

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

});

我用jquery解决了它:

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

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

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

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

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

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

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

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

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

这个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 < /选项> < /选择>