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

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

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


当前回答

简单jQuery解决方案

如果你选择的是只读类,使用这个选项

jQuery('select.readonly option:not(:selected)').attr('disabled',true);

或者如果你的选择有readonly="readonly"属性

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

其他回答

(简单的解决方案)

由于OP特别要求他不想禁用select元素,下面是我用来使select变为只读的方法

在html中

<select style="pointer-events: none;" onclick="return false;" onkeydown="return false;" ></select>

就是这样

解释

将pointer-events设置为none将禁用使用鼠标/光标事件编辑“select-element” 设置onclick和onkeydown函数返回false将禁用使用键盘编辑“select-element”

通过这种方式,您不必创建任何额外的元素,或使用javascript禁用/重新启用元素,或打乱表单提交逻辑,或使用任何第三方库。

此外,您可以轻松地添加css样式,如设置背景颜色为灰色或文本颜色为灰色,以暗示该元素是只读的。我没有将它添加到代码中,因为它非常特定于您的站点主题

或者你想通过javascript来实现

let isReadOnly = true; selectElement。Onclick = function () { isReadOnly; }; selectElement。onkeydown = function () { isReadOnly; }; selectElement.style.pointerEvents = isReadOnly ?“none”:“全部”;

这可能在某种程度上与其他解决方案类似,但简化为更少的行数。

假设有一个jquery函数禁用目标选项…

$("select[id='country']").val('PH').attr("disabled", true);
$("select[id='country']").parent().append("<input type='hidden' id='country' value='PH'>");

如果你想重新启用这个选项…

$("select[id='country']").attr("disabled", false);
$("input[id='country']").remove();

根据格兰特·瓦格纳的建议;下面是一个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);
        }
    });

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

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

我通过隐藏选择框并在其位置显示一个只有信息值的span来管理它。在禁用.readonly类的事件中,我们还需要删除. tovanish元素并显示. toshow元素。

 $( '.readonly' ).live( 'focus', function(e) {
                $( this ).attr( 'readonly', 'readonly' )
                if( $( this ).get(0).tagName == 'SELECT' ) {
                    $( this ).before( '<span class="toVanish readonly" style="border:1px solid; padding:5px">' 
                            + $( this ).find( 'option:selected' ).html() + '</span>' )
                    $( this ).addClass( 'toShow' )
                    $( this ).hide()
            }
    });