我有一个简单的问题就是我。我已经看过很多例子但是我不能把手指放在正确的代码上。问题:我只有在从下拉列表中选择“其他”时才需要显示文本输入字段。
我的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>
}
}
下拉列表在回发到控制器时正常工作,但我想显示描述输入框。没有看到任何会复制这种行为的东西(不管怎么说都不在我的搜索中)。一如往常任何帮助将不胜感激!
答案 0 :(得分:2)
您设置showGenderDescription
的方式,只会检查一次。要将其绑定到任何更改,请使用类(或类似)来包装“其他”输入字段:
<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();
}
答案 1 :(得分:1)
我为编辑添加了父div,并更改了Jquery功能。如果有任何问题,请告诉我
<强>脚本强>
<script>
$(function () {
$("#ShowGenderDescriptionContainer").css("display","none");
$('#GenderId').change(function () {
if ($("#GenderId").val() == 3) {
$("#ShowGenderDescriptionContainer").css("display","block");
}
});
$("#SettingId").change(function () {
if ($("#SettingId").val() == 1) {
$("#ShowGenderDescriptionContainer").css("display","block");
}
});
});
</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>
<div id = "ShowGenderDescriptionContainer">
<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>
}