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

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

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


当前回答

简单的CSS解决方案:

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

select[readonly] option{
    display: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();

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

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

我通过隐藏选择框并在其位置显示一个只有信息值的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()
            }
    });

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

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

jQuery示例:

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

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

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

“选择多个”对上述代码建议的响应几乎没有那么好。经过大量的推敲和拼凑,我最终得到了这个:

var thisId="";
var thisVal="";
function selectAll(){
    $("#"+thisId+" option").each(function(){
        if(!$(this).prop("disabled"))$(this).prop("selected",true);
    });
    $("#"+thisId).prop("disabled",false);
}
$(document).ready(function(){
    $("select option:not(:selected)").attr('disabled',true);
    $("select[multiple]").focus(function(){
        thisId=$(this).prop("id");
        thisVal=$(this).val();
        $(this).prop("disabled",true).blur();
        setTimeout("selectAll();",200);
    });
});