根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
根据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.myselect").bind("focus", function(){
if($(this).hasClass('readonly'))
{
$(this).blur();
return;
}
});
<select id="case_reason" name="case_reason" disabled="disabled">
Disabled =" Disabled " ->将从数据库中获取你的值,但在表单中显示它。 Readonly =" Readonly " ->你可以在选择框中更改你的值,但你的值不能保存在你的数据库中。
这是最简单、最好的解决办法。 您将在您的选择上设置一个readolny属性,或任何其他属性,如data-readonly,并执行以下操作
$("select[readonly]").live("focus mousedown mouseup click",function(e){
e.preventDefault();
e.stopPropagation();
});
“选择多个”对上述代码建议的响应几乎没有那么好。经过大量的推敲和拼凑,我最终得到了这个:
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);
});
});
我知道这已经太迟了,但它可以用简单的CSS完成:
select[readonly] option, select[readonly] optgroup {
display: none;
}
当选择处于只读状态时,样式会隐藏所有选项和组,因此用户不能更改他的选择。
不需要JavaScript技巧。