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

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

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


当前回答

如果你正在使用jquery验证,你可以做下面的事情,我使用disabled属性没有问题:

$(function(){
    $('#myform').validate({
        submitHandler:function(form){
            $('select').removeAttr('disabled');
            form.submit();
        }
    });
});

其他回答

您可以禁用除当前选中的选项以外的所有选项,而不是选择本身。这提供了一个工作的下拉菜单的外观,但只有您想要传递的选项是有效的选择。

如果选择下拉菜单自诞生以来是只读的,根本不需要更改,也许您应该使用另一个控件?比如一个简单的<div>(加上隐藏的表单字段)或一个<input type="text">?

补充:如果下拉菜单不是一直都是只读的,并且JavaScript被用来启用/禁用它,那么这仍然是一个解决方案——只需要动态修改DOM。

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

});

我们还可以禁用除所选选项之外的所有选项。

这样,下拉菜单仍然可以工作(并提交其值),但用户不能选择其他值。

Demo

<选择> <选项禁用> 1 > < /选项 <选项> 2 > < /选项 <选项禁用> 3 < /选项> < /选择>

我的解决方案是添加select[readonly] {pointer-events: none;}样式,然后添加这个JS来处理键盘事件:

$(document).on('keydown', 'select[readonly]', function(e) {
    if (e.keyCode != 9) {
        if (e.preventDefault) {
            e.preventDefault();
        }

        e.returnValue = false;
        e.cancel = true;
    }
});

这仍然允许遍历带有tab的元素。