我有一个选择表单字段,我想标记为“readonly”,因为用户不能修改该值,但该值仍然与表单一起提交。使用disabled属性可以防止用户更改值,但不会将值与表单一起提交。
readonly属性仅适用于输入和文本区域字段,但这基本上是我想要的。有办法让它工作吗?
我考虑的两种可能性包括:
不是禁用选择,而是禁用所有选项,并使用CSS将选择变成灰色,这样它看起来就像禁用了一样。 向提交按钮添加单击事件处理程序,以便在提交表单之前启用所有禁用的下拉菜单。
我有一个选择表单字段,我想标记为“readonly”,因为用户不能修改该值,但该值仍然与表单一起提交。使用disabled属性可以防止用户更改值,但不会将值与表单一起提交。
readonly属性仅适用于输入和文本区域字段,但这基本上是我想要的。有办法让它工作吗?
我考虑的两种可能性包括:
不是禁用选择,而是禁用所有选项,并使用CSS将选择变成灰色,这样它看起来就像禁用了一样。 向提交按钮添加单击事件处理程序,以便在提交表单之前启用所有禁用的下拉菜单。
当前回答
我使用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');
});
其他回答
我发现最简单的方法是创建一个小的javascript函数绑定到你的表单:
function enablePath() {
document.getElementById('select_name').disabled= "";
}
你在这里的表格中称它为
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
或者你可以在你用来检查你的表单的函数中调用它:)
<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");
}
在提交前添加一行即可。
$(“#XYZ”).removeAttr(“disabled”);
<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');
});