根据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);
});
其他回答
var selectedOpt;//initialize var var newIdForHidden;//initialize var $('.disabledOnEdit').focusin(function(){ selectedOpt = $(this).find(":selected").val(); newIdForHidden = $(this).attr('id')+'Hidden'; //alert(selectedOpt+','+newIdForHidden); $(this).append(''); $(this).find('input.hiddenSelectedOpt').attr('id',newIdForHidden).val(selectedOpt); }); $('.disabledOnEdit').focusout(function(){ var oldSelectedValue=$(this).find('input.hiddenSelectedOpt').val(); $(this).val(oldSelectedValue); });
我用jquery解决了它:
$("select.myselect").bind("focus", function(){
if($(this).hasClass('readonly'))
{
$(this).blur();
return;
}
});
我通过隐藏选择框并在其位置显示一个只有信息值的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()
}
});
使用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();
});
简单的CSS解决方案:
select[readonly]{
background: #eee;
cursor:no-drop;
}
select[readonly] option{
display:none;
}
这导致在选择是灰色的漂亮的“禁用”光标悬停 在选择选项列表是“空”,所以你不能改变它的值。