根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
当前回答
还有一个更现代的选项(没有双关语的意思)是禁用选择元素的所有选项,除了选中的选项。
但是请注意,这是一个HTML 4.0特性 而ie 6 7 8 1似乎不符合这个。
http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html
其他回答
我通过隐藏选择框并在其位置显示一个只有信息值的span来管理它。在禁用.readonly类的事件中,我们还需要删除. tovanish元素并显示. toshow元素。
$( '.readonly' ).live( 'focus', function(e) {
$( this ).attr( 'readonly', 'readonly' )
if( $( this ).get(0).tagName == 'SELECT' ) {
$( this ).before( '<span class="toVanish readonly" style="border:1px solid; padding:5px">'
+ $( this ).find( 'option:selected' ).html() + '</span>' )
$( this ).addClass( 'toShow' )
$( this ).hide()
}
});
您可以禁用除当前选中的选项以外的所有选项,而不是选择本身。这提供了一个工作的下拉菜单的外观,但只有您想要传递的选项是有效的选择。
这个javascript找到所有的'select'与'readonly'属性,然后把disabled在'options'除了selected(回发)
文档。querySelectorAll("select[readonly] > option:not([selected])")。forEach((el) => el。setAttribute("disabled", "disabled")); 不带readonly: <select> <选项> 1 > < /选项 <选项> 2 > < /选项 <选项> 3 < /选项> < /选择> < br > 带readonly: <select readonly="readonly"> <选项> 1 > < /选项 <选项> 2 > < /选项 <选项> 3 < /选项> < /选择>
下面是一个尝试使用自定义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);
});
这可能在某种程度上与其他解决方案类似,但简化为更少的行数。
假设有一个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();