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

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

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

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


当前回答

我找到了一个可行的解决方案:删除所有的元素,除了选中的元素。然后,您可以将样式更改为看起来也不完善的样式。 使用jQuery:

jQuery(function($) {
    $('form').submit(function(){
        $('select option:not(:selected)', this).remove();
    });
});

其他回答

<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,你把它放在后面。一如既往,测试是关键。

基于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");

我使用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');
});

对于选择字段,它不能使用:input选择器,使用这个:

    jQuery(function() {

    jQuery('form').bind('submit', function() {
        jQuery(this).find(':disabled').removeAttr('disabled');
    });

    });

我找到了一个可行的解决方案:删除所有的元素,除了选中的元素。然后,您可以将样式更改为看起来也不完善的样式。 使用jQuery:

jQuery(function($) {
    $('form').submit(function(){
        $('select option:not(:selected)', this).remove();
    });
});