根据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
其他回答
输入为<select>元素:
input.querySelectorAll(':not([selected])').forEach(option => {
option.disabled = true
})
这将保留数据中的选择(因为它没有被禁用),并且只有未被选中的选项是禁用的,因此是不可选的。 结果是一个不可更改的可读选择(=>只读)。
非常简单。首先将值存储在变量中。然后将事件集的值更改为存储的变量,该变量包含的初始值
我有一个名字是映射的。那么我的代码将如下所示;
$("document").ready(function(){
var mapping=$("select[name=mapping]").val();
$("select[name=mapping]").change(function(){
$("select[name=mapping]").val(mapping);
});
});
我知道这不会帮助每个人(如果你只是客户端),但会帮助一些全栈和控制后端以及前端的人。
如果用户没有编辑字段的特权,我只返回下拉列表的当前选择。
以下是我的后端控制器:
#region Prepare Action Priviledges
editAuditVM.ExtAuditEditRoleMatrixVM = new ExtAuditEditRoleMatrixVM
{
CanEditAcn = _extAuditEditRoleMatrixHelper.CanEditAcn(user, audit),
CanEditSensitiveDesignation = _extAuditEditRoleMatrixHelper.CanEditSensitiveDesignation(user, audit),
CanEditTitle = _extAuditEditRoleMatrixHelper.CanEditTitle(),
CanEditAuditScope = _extAuditEditRoleMatrixHelper.CanEditAuditScope(user, audit)
};
#endregion
#region Prepare SelectLists for Drop Downs
#region AuditScope List
IQueryable<SelectListItem> auditScopes = _auditTypesRepo.AuditTypes
.Where(at => at.AuditTypeClassCode.ToLower() == "e")
.Select(at => new SelectListItem
{ Text = at.AuditTypeText, Value = at.AuditTypeID.ToString() });
// Cannot make a select readonly on client side.
// So only return currently selected option.
if (!editAuditVM.ExtAuditEditRoleMatrixVM.CanEditAuditScope)
{
auditScopes = auditScopes
.Where(ascopeId => ascopeId.Value == editAuditVM.ExternalAudit.AuditTypeID.ToString());
}
#endregion
#endregion
以下是对我有用的:
$('select[name=country]').attr("disabled", "disabled");
我的解决方案是添加select[readonly] {pointer-events: none;}样式,然后添加这个JS来处理键盘事件:
$(document).on('keydown', 'select[readonly]', function(e) {
if (e.keyCode != 9) {
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
e.cancel = true;
}
});
这仍然允许遍历带有tab的元素。