我正在建立一个注册表单,其中有一个安全问题的下拉列表。用户可以选择各种问题,但是,我在列表中有一个项目“[输入您自己的问题]”。
当用户选择“[输入您自己的问题]”时,我想要显示一个css隐藏文本框。
以下是我的Register.cshtml剃刀格式中的代码:
<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名称中取出@符号和其他各种东西,但仍然没有运气。这里有人看到我的代码有问题吗?
非常感谢!
答案 0 :(得分:3)
首先,您需要在DOM准备就绪时运行代码,为此,将代码包装在一个就绪处理程序中:$(function() { ... }
。其次,最好检查选择的value
而不是selectedIndex
,以防将来选项的顺序发生变化。
<script type="text/javascript">
$(function() {
$("#ddlSq1").change(function () {
if ($(this).val() == "SQ6")
$("#customSecurity").css("visibility", "visible");
});
});
</script>
答案 1 :(得分:0)
将此代码移至$(document).ready()
<script type="text/javascript">
$(document).ready(function(){
$("#ddlSq1").change(function () {
if ($(this).attr('selectedIndex') == 5)
$("#customSecurity").css("visibility", "visible");
});
});
</script>