当从 DDL 中选择“其他”时,我只想显示文本框。但是它总是显示而不是隐藏直到被调用。
我的 View 标记是:
<div class="form-group">
@Html.LabelFor(model => model.SelectType, "Select Type", new { @class = "control-label col-md-5" })
<div class="col-md-1">
@Html.DropDownList("SelectType", null, new { @id = "Other" })
@Html.TextBoxFor(model => model.OtherSpecify, new { @id = "OtherSpecify" })
@Html.ValidationMessageFor(model => model.SelectType)
</div>
我尝试了以下两个 javacript 代码都没有成功
<script>
document.addEventListener("DOMContentLoaded", function () {
$("SelectType").trigger("change");
})
$("#SelectType").on("change", function () {
if ($("#SelectType option:selected").val() == 3) {
$("#OtherSpecify").hide();
} else {
$("#OtherSpecify").show();
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () { $("SelectType").trigger("change");
})
$(function () {
$('.OtherSpecify').show();
$("Other").change(function () {
if ($(this).is(":selected")) {
$(this).parent().next().hide();
}
else {
$(this).parent().next().show();
}
});
})
</script>
最佳答案
首先你应该检查如何jQuery selectors工作。
在上面的 HTML 中,'$("#SelectType")' - 是您的选择,$("#OtherSpecify")
是您的文本框。
如果你正在使用 jQuery,你应该一直使用它。
使用 $(handler)已安装 DOMContentLoaded
事件:
<div class="form-group">
<div class="col-md-1">
@Html.DropDownList("SelectType", new List<SelectListItem> {
new SelectListItem{Text = "test 1", Value = "1"},
new SelectListItem{Text = "test 2", Value = "2"},
new SelectListItem{Text = "Other", Value = "3"}
}, new { @id = "SelectType" })
@Html.TextBox("OtherSpecify", "")
</div>
</div>
@section Scripts {
<script>
$(function() {
$("#SelectType").on("change", function() {
if (parseInt($("#SelectType").val()) == 3) {
$("#OtherSpecify").show();
} else {
$("#OtherSpecify").hide();
}
});
$("#SelectType").trigger("change");
});
</script>
}
请记住在加载 jQuery 库后放置脚本。在大多数情况下,@section Scripts
完成工作。
关于javascript - 当从 MVC 的下拉列表中选择一个值时出现一个文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880699/