我有一个简单的问题,只是我无法解决。我看过很多示例,但就是无法确定正确的代码。问题:仅当从下拉列表中选择“其他”时,我才需要显示文本输入字段。
我的 JavaScript:
@{
ViewBag.Title = "Create Client";
var showGenderDescription = false;
var showSettingDescription = false;
}
<script src="~/Scripts/jquery-2.0.3.js"></script>
<script>
$(function () {
$('#GenderId').change(function () {
if ($("#GenderId").val() == 3) {
showGenderDescription = true;
}
});
$("#SettingId").change(function () {
if ($("#SettingId").val() == 1) {
showGenderDescription = true;
}
});
});
</script>
我的查看代码:
@using (Html.BeginForm())
{
<div class="editor-label">
@Html.LabelFor(model => model.GenderId, "Gender")
</div>
<div class="editor-field">
@Html.DropDownList("GenderId", (SelectList)ViewBag.GenderId, "--Select One--", new { id = "GenderId"})
@Html.ValidationMessageFor(model => model.GenderId)
</div>
@if(showGenderDescription)
{
<div class="editor-label">
@Html.LabelFor(model => model.GenderDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.GenderDescription)
@Html.ValidationMessageFor(model => model.GenderDescription)
</div>
}
}
下拉列表在发回 Controller 时可以正常工作,但我想显示描述输入框。还没有看到任何会重复这种行为的东西(无论如何不在我的搜索中)。一如既往,我们将不胜感激!
最佳答案
您设置showGenderDescription
的方式只会检查一次。要将它绑定(bind)到任何更改,请使用一个类(或类似的)来包装“其他”输入字段:
<div class="gender-description">
<div class="editor-label">
@Html.LabelFor(model => model.GenderDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.GenderDescription)
@Html.ValidationMessageFor(model => model.GenderDescription)
</div>
</div>
然后你可以在 change
JS 函数中显示/隐藏它:
if ($("#GenderId").val() == 3) {
$(".gender-description").show();
} else {
$(".gender-description").hide();
}
关于javascript - MVC4 从下拉列表中选择 'other' 时显示描述字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18295137/