根据HTML规范,HTML中的select
标签没有readonly
属性,只有disabled
属性。 因此,如果要阻止用户更改下拉菜单,则必须使用disabled
。
唯一的问题是禁用的HTML表单输入不会包含在POST / GET数据中。
模拟select
标签的readonly
属性并仍然获取POST数据的最佳方法是什么?
#1楼
简单的jQuery解决方案
如果您的选择具有readonly
类,请使用此选项
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
如果您的选择具有readonly="readonly"
属性,则为此属性
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
#2楼
这是尝试使用自定义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);
});
#3楼
如果您正在使用jquery validate,则可以执行以下操作,我使用了disable属性没有问题:
$(function(){
$('#myform').validate({
submitHandler:function(form){
$('select').removeAttr('disabled');
form.submit();
}
});
});
#4楼
一种简单的服务器端方法是删除所有要选择的选项之外的选项。 因此,在Zend Framework 1.12中,如果$ element是Zend_Form_Element_Select:
$value = $element->getValue();
$options = $element->getAttrib('options');
$sole_option = array($value => $options[$value]);
$element->setAttrib('options', $sole_option);
#5楼
除了禁用不应选择的选项外,我还想使它们从列表中消失,但仍然可以启用它们,以备以后使用:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
此查找所有选择元素与只读属性,然后查找未选择那些选择内的所有选项,然后将其隐藏它们和禁用它们。
它分开在2由于性能原因jQuery的查询,因为jQuery他们读从右到左,代码是非常重要的:
$("select[readonly] option:not(:selected)")
首先将找到文档中所有未选择的选项,然后使用只读属性过滤select内的所有未选择选项。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3156209