我正在构建一个注册表单,其中有一个安全问题的下拉列表。用户可以选择各种问题,但是,列表中有一个项目显示“[输入您自己的问题]”。
我有一个 css 隐藏文本框,我想在用户选择“[输入您自己的问题]”时显示该文本框。
这是我的 Register.cshtml razor 表单中的代码:
<div class="editor-field">
@{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "What was the name of your first pet?", Value = "SQ1" });
items.Add(new SelectListItem { Text = "What is your mother's maiden name?", Value = "SQ2" });
items.Add(new SelectListItem { Text = "What was the first foreign country you visited?", Value = "SQ3" });
items.Add(new SelectListItem { Text = "What is your favorite sports team?", Value = "SQ4" });
items.Add(new SelectListItem { Text = "Who is your favorite athlete?", Value = "SQ5" });
items.Add(new SelectListItem { Text = "[Type in your own question]", Value = "SQ6" });
}
@Html.DropDownListFor(model => model.SecurityQuestion1, items, new { @Id = "ddlSq1" })
@Html.ValidationMessageFor(model => model.AnswerSecurityQuestion1)
</div>
<div id="customSecurity" style="visibility:hidden">
<div class="editor-label">
@Html.LabelFor(model => model.CustomSecurityQuestion1)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.CustomSecurityQuestion1, new { @Id="txtCustomSq1"})
@Html.ValidationMessageFor(model => model.CustomSecurityQuestion1)
</div>
这是我的 jquery/javascript:
<script type="text/javascript">
$("#ddlSq1").change(function () {
if ($(this).attr('selectedIndex') == 5)
$("#customSecurity").css("visibility", "visible");
});
</script>
.change 事件根本没有触发。我不知道它会是什么。我尝试从 html 助手和其他各种东西中的 ID 命名中取出 @ 符号,但仍然没有成功。这里有人发现我的代码有问题吗?
非常感谢!
最佳答案
首先,您需要在 DOM 准备就绪时运行代码,为此,请将代码包装在准备好的处理程序中:$(function() { ... }
。其次,最好检查 select 的 value
而不是 selectedIndex
,以防将来选项的顺序发生变化。
<script type="text/javascript">
$(function() {
$("#ddlSq1").change(function () {
if ($(this).val() == "SQ6")
$("#customSecurity").css("visibility", "visible");
});
});
</script>
关于jquery - 根据下拉列表选择显示表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10636102/