我有一个选择表单字段,我想标记为“readonly”,因为用户不能修改该值,但该值仍然与表单一起提交。使用disabled属性可以防止用户更改值,但不会将值与表单一起提交。

readonly属性仅适用于输入和文本区域字段,但这基本上是我想要的。有办法让它工作吗?

我考虑的两种可能性包括:

不是禁用选择,而是禁用所有选项,并使用CSS将选择变成灰色,这样它看起来就像禁用了一样。 向提交按钮添加单击事件处理程序,以便在提交表单之前启用所有禁用的下拉菜单。


当前回答

基于Jordan的解决方案,我创建了一个函数,它自动创建一个隐藏输入,该输入具有与您希望无效的select相同的名称和相同的值。第一个参数可以是id或者jquery元素;第二个是布尔可选参数,其中“true”禁用输入,“false”启用输入。如果省略,第二个参数将在“enabled”和“disabled”之间切换选择。

function changeSelectUserManipulation(obj, disable){
    var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
    disable = disable? !!disable : !$obj.is(':disabled');

    if(disable){
        $obj.prop('disabled', true)
            .after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
    }else{
        $obj.prop('disabled', false)
            .next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
    }
}

changeSelectUserManipulation("select_id");

其他回答

我遇到了一个略有不同的场景,在这种场景中,我只想不允许用户根据先前的选择框更改所选值。我最终所做的只是禁用所有其他非选择选项在选择框使用

$('#toSelect').find(':not(:selected)').prop('disabled',true);

我制作了一个快速(Jquery only)插件,当输入被禁用时,将值保存在数据字段中。 这只是意味着,只要该字段通过jquery使用.prop()或.attr()被程序化禁用…然后通过.val(), .serialize()或.serializeArra()访问该值将始终返回该值,即使禁用:)

无耻插头:https://github.com/Jezternz/jq-disabled-inputs

<select id="example">
    <option value="">please select</option>
    <option value="0" >one</option>
    <option value="1">two</option>
</select>



if (condition){
    //you can't select
    $("#example").find("option").css("display","none");
}else{
   //you can select
   $("#example").find("option").css("display","block");
}
<select disabled="disabled">
    ....
</select>
<input type="hidden" name="select_name" value="selected value" />

其中select_name是<select>通常使用的名称。

另一种选择。

<select name="myselect" disabled="disabled">
    <option value="myselectedvalue" selected="selected">My Value</option>
    ....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />

现在有了这个,我注意到根据你使用的web服务器,你可能必须把隐藏输入放在<select>之前或之后。

如果我没记错的话,对于IIS,你把它放在前面,对于Apache,你把它放在后面。一如既往,测试是关键。

我使用next代码禁用选择中的选项

<select class="sel big" id="form_code" name="code" readonly="readonly">
   <option value="user_played_game" selected="true">1 Game</option>
   <option value="coins" disabled="">2 Object</option>
   <option value="event" disabled="">3 Object</option>
   <option value="level" disabled="">4 Object</option>
   <option value="game" disabled="">5 Object</option>
</select>

// Disable selection for options
$('select option:not(:selected)').each(function(){
 $(this).attr('disabled', 'disabled');
});