我在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。但如果有人可以帮助我,那就很好。
答案 0 :(得分:2)
2分。
你有2个相同的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';
}
});
};