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

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

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


当前回答

我知道这已经太迟了,但它可以用简单的CSS完成:

select[readonly] option, select[readonly] optgroup {
    display: none;
}

当选择处于只读状态时,样式会隐藏所有选项和组,因此用户不能更改他的选择。

不需要JavaScript技巧。

其他回答

<select id="case_reason" name="case_reason" disabled="disabled">

Disabled =" Disabled " ->将从数据库中获取你的值,但在表单中显示它。 Readonly =" Readonly " ->你可以在选择框中更改你的值,但你的值不能保存在你的数据库中。

摘自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','');
}

模拟select的readonly属性的最佳方法是什么 标签,仍然得到POST数据?

只要让它成为一个输入/文本字段,并添加'readonly'属性。如果select被有效地“禁用”,那么无论如何您都不能更改该值,因此您不需要select标记,您可以简单地将“selected”值显示为只读文本输入。对于大多数UI目的,我认为这应该足够了。

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

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

您可以在提交时重新启用选择对象。

EDIT:也就是说,通常禁用select标签(带有disabled属性),然后在提交表单之前自动重新启用它:

jQuery示例:

禁用: $ (" # yourSelect”)。道具(“禁用”,真正的); 在提交前重新启用GET / POST数据: $ (" # yourForm”)。On ('submit', function() { $ (" # yourSelect”)。道具(“禁用”,假); });

此外,您可以重新启用每个禁用的输入或选择:

$('#yourForm').on('submit', function() {
    $('input, select').prop('disabled', false);
});