根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。
唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。
什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?
当前回答
简单: 添加样式属性到你的选择标签:
style="pointer-events: none;"
其他回答
如果你禁用了一个表单字段,当表单被提交时,这将不会被发送。 所以如果你需要一个像disabled一样工作但发送值的readonly,可以这样做:
在元素的只读属性发生任何变化之后。
$('select.readonly option:not(:selected)').attr('disabled',true);
$('select:not([readonly]) option').removeAttr('disabled');
我知道这不会帮助每个人(如果你只是客户端),但会帮助一些全栈和控制后端以及前端的人。
如果用户没有编辑字段的特权,我只返回下拉列表的当前选择。
以下是我的后端控制器:
#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
所以无论出于什么原因,这里提到的所有基于jquery的解决方案都不适合我。所以这里是一个纯javascript的解决方案,它也应该在做POST时保留所选的值。
setDropdownReadOnly('yourIdGoesHere',true/false)
函数setDropdownReadOnly(controlName, state) { var ddl = document.getElementById(controlName); For (i = 0;I < ddl.length;我+ +){ if (i == ddl.selectedIndex) ddl[我]。禁用= false; 其他的 ddl[我]。禁用=状态; } }
<select id="case_reason" name="case_reason" disabled="disabled">
Disabled =" Disabled " ->将从数据库中获取你的值,但在表单中显示它。 Readonly =" Readonly " ->你可以在选择框中更改你的值,但你的值不能保存在你的数据库中。
根据格兰特·瓦格纳的建议;下面是一个jQuery代码片段,它使用处理函数而不是直接使用onXXX属性:
var readonlySelect = function(selector, makeReadonly) {
$(selector).filter("select").each(function(i){
var select = $(this);
//remove any existing readonly handler
if(this.readonlyFn) select.unbind("change", this.readonlyFn);
if(this.readonlyIndex) this.readonlyIndex = null;
if(makeReadonly) {
this.readonlyIndex = this.selectedIndex;
this.readonlyFn = function(){
this.selectedIndex = this.readonlyIndex;
};
select.bind("change", this.readonlyFn);
}
});
};