根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
当前回答
<select id="case_reason" name="case_reason" disabled="disabled">
Disabled =" Disabled " ->将从数据库中获取你的值,但在表单中显示它。 Readonly =" Readonly " ->你可以在选择框中更改你的值,但你的值不能保存在你的数据库中。
其他回答
我们还可以禁用除所选选项之外的所有选项。
这样,下拉菜单仍然可以工作(并提交其值),但用户不能选择其他值。
Demo
<选择> <选项禁用> 1 > < /选项 <选项> 2 > < /选项 <选项禁用> 3 < /选项> < /选择>
<select id="case_reason" name="case_reason" disabled="disabled">
Disabled =" Disabled " ->将从数据库中获取你的值,但在表单中显示它。 Readonly =" Readonly " ->你可以在选择框中更改你的值,但你的值不能保存在你的数据库中。
使用tabindex解决方案。适用于选择和文本输入。
简单地使用.disabled类。
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
编辑:使用Internet Explorer,你还需要这个JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
这可能在某种程度上与其他解决方案类似,但简化为更少的行数。
假设有一个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();
根据格兰特·瓦格纳的建议;下面是一个jQuery代码片段,它使用处理函数而不是直接使用onXXX属性:
var readonlySelect = function(selector, makeReadonly) {
$(selector).filter("select").each(function(i){
var select = $(this);
//remove any existing readonly handler
if(this.readonlyFn) select.unbind("change", this.readonlyFn);
if(this.readonlyIndex) this.readonlyIndex = null;
if(makeReadonly) {
this.readonlyIndex = this.selectedIndex;
this.readonlyFn = function(){
this.selectedIndex = this.readonlyIndex;
};
select.bind("change", this.readonlyFn);
}
});
};