根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
当前回答
下面是一个尝试使用自定义jQuery函数来实现的功能(如这里所述):
$(function(){
$.prototype.toggleDisable = function(flag) {
// prepare some values
var selectId = $(this).attr('id');
var hiddenId = selectId + 'hidden';
if (flag) {
// disable the select - however this will not submit the value of the select
// a new hidden form element will be created below to compensate for the
// non-submitted select value
$(this).attr('disabled', true);
// gather attributes
var selectVal = $(this).val();
var selectName = $(this).attr('name');
// creates a hidden form element to submit the value of the disabled select
$(this).parents('form').append($('<input></input>').
attr('type', 'hidden').
attr('id', hiddenId).
attr('name', selectName).
val(selectVal) );
} else {
// remove the newly-created hidden form element
$(this).parents('form').remove(hiddenId);
// enable back the element
$(this).removeAttr('disabled');
}
}
// Usage
// $('#some_select_element').toggleDisable(true);
// $('#some_select_element').toggleDisable(false);
});
其他回答
简单地说,在提交表单之前删除disabled属性。
$('form').submit(function () {
$("#Id_Unidade").attr("disabled", false);
});
(简单的解决方案)
由于OP特别要求他不想禁用select元素,下面是我用来使select变为只读的方法
在html中
<select style="pointer-events: none;" onclick="return false;" onkeydown="return false;" ></select>
就是这样
解释
将pointer-events设置为none将禁用使用鼠标/光标事件编辑“select-element” 设置onclick和onkeydown函数返回false将禁用使用键盘编辑“select-element”
通过这种方式,您不必创建任何额外的元素,或使用javascript禁用/重新启用元素,或打乱表单提交逻辑,或使用任何第三方库。
此外,您可以轻松地添加css样式,如设置背景颜色为灰色或文本颜色为灰色,以暗示该元素是只读的。我没有将它添加到代码中,因为它非常特定于您的站点主题
或者你想通过javascript来实现
let isReadOnly = true; selectElement。Onclick = function () { isReadOnly; }; selectElement。onkeydown = function () { isReadOnly; }; selectElement.style.pointerEvents = isReadOnly ?“none”:“全部”;
除了禁用不应该是可选的选项,我想实际上让他们从列表中消失,但仍然能够启用他们,我应该以后需要:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
它会找到所有带有只读属性的select元素,然后找到那些未被选中的select元素中的所有选项,然后隐藏它们并禁用它们。
出于性能考虑,将jquery查询分为2是很重要的,因为jquery从右向左读取它们,代码如下:
$("select[readonly] option:not(:selected)")
将首先找到文档中所有未选中的选项,然后筛选那些在具有只读属性的选择内的选项。
这可能在某种程度上与其他解决方案类似,但简化为更少的行数。
假设有一个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();
我知道这已经太迟了,但它可以用简单的CSS完成:
select[readonly] option, select[readonly] optgroup {
display: none;
}
当选择处于只读状态时,样式会隐藏所有选项和组,因此用户不能更改他的选择。
不需要JavaScript技巧。