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

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

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


当前回答

以下是对我有用的:

$('select[name=country]').attr("disabled", "disabled"); 

其他回答

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

摘自https://stackoverflow.com/a/71086058/18183749

如果你不能使用'disabled'属性(因为它会擦除值的 input at POST),并注意到html属性'readonly'只工作 在文本区域和一些输入(文本,密码,搜索,据我所见), 最后,如果你不想重复你所有的 您可能会发现,带有隐藏输入逻辑的选择、复选框和单选 下面的函数或任何他的内部逻辑你喜欢:

addReadOnlyToFormElements = function (idElement) {
    
        // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
        $('#' + idElement + ' select>option:not([selected])').prop('disabled',true);
    
        // and, on the selected ones, to mimic readOnly appearance
        $('#' + idElement + ' select').css('background-color','#eee');
    }

没有什么比删除这些只读更容易的了

removeReadOnlyFromFormElements = function (idElement) {

    // Remove the disabled attribut on non-selected 
    $('#' + idElement + ' select>option:not([selected])').prop('disabled',false);

    // Remove readOnly appearance on selected ones
    $('#' + idElement + ' select').css('background-color','');
}

根据格兰特·瓦格纳的建议;下面是一个jQuery代码片段,它使用处理函数而不是直接使用onXXX属性:

var readonlySelect = function(selector, makeReadonly) {

    $(selector).filter("select").each(function(i){
        var select = $(this);

        //remove any existing readonly handler
        if(this.readonlyFn) select.unbind("change", this.readonlyFn);
        if(this.readonlyIndex) this.readonlyIndex = null;

        if(makeReadonly) {
            this.readonlyIndex = this.selectedIndex;
            this.readonlyFn = function(){
                this.selectedIndex = this.readonlyIndex;
            };
            select.bind("change", this.readonlyFn);
        }
    });

};

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

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

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

简单的CSS解决方案:

select[readonly]{
    background: #eee;
    cursor:no-drop;
}

select[readonly] option{
    display:none;
}

这导致在选择是灰色的漂亮的“禁用”光标悬停 在选择选项列表是“空”,所以你不能改变它的值。