我在Register.cshtml中有以下表格
<div class="form-group" id="Nick">
@Html.LabelFor(m => m.Nickname, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Nickname, new { @class = "form-control" })
</div>
</div>
<div class="form-group" id="Company">
@Html.LabelFor(m => m.CompanyName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.CompanyName, new { @class = "form-control" })
</div>
</div>
<div class="form-group" onchange="Show()">
@Html.Label("Select Your Role", new { @class = "col-md-2 control-label", @id = "ddlRoleId"})
<div class="col-md-10">
@Html.DropDownListFor(model => model.Role, Model.RoleList, htmlAttributes: new { @class = "form-control", @id = "ddlRoleId" })
</div>
</div>
和
<script language="JavaScript" type="text/javascript">
function Show() {
var ddl = document.getElementById('ddlRoleId'),
Nickform = document.getElementById('Nick'),
CompanyForm = document.getElementById('Company');
ddl.addEventListener('change', function () {
if (this.value === '1') {
Nickform.style.display = 'none';
CompanyForm.style.display = 'block';
}
else {
Nickform.style.display = 'block';
CompanyForm.style.display = 'none';
}
if (this.value === '2') {
CompanyForm.style.display = 'none';
Nickform.style.display = 'block';
}
else {
CompanyForm.style.display = 'block';
Nickform.style.display = 'none';
}
});
};
</script>
我想从两种形式(公司/昵称)中选择一个角色来隐藏。
但是上面的代码不起作用。我找不到我犯错的地方。可能位于DropDownList。但是,如果有人可以帮助我,那会很好。
最佳答案
2分。
您有2个ID相同。标签,且下拉菜单的ID为ddlRoleId
。我假设您要标签for="ddlRoleId"
而不是id="ddlRoleId"
另外,我看不到您在哪里呼叫Show()
。尝试用window.onload = function () {
替换该行。或在show函数之后添加window.onload = Show();
。
所以:-
window.onload = function () {
var ddl = document.getElementById('ddlRoleId'),
Nickform = document.getElementById('Nick'),
CompanyForm = document.getElementById('Company');
ddl.addEventListener('change', function () {
if (this.value === '1') {
Nickform.style.display = 'none';
CompanyForm.style.display = 'block';
}
else {
Nickform.style.display = 'block';
CompanyForm.style.display = 'none';
}
if (this.value === '2') {
CompanyForm.style.display = 'none';
Nickform.style.display = 'block';
}
else {
CompanyForm.style.display = 'block';
Nickform.style.display = 'none';
}
});
};
关于jquery - 从下拉列表中选择值时隐藏字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32789768/