2

我正在构建一个注册表单,其中有一个安全问题的下拉列表。用户可以选择各种问题,但是,我在列表中有一个项目,上面写着“[输入您自己的问题]”。

我有一个 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 命名中取出,但仍然没有运气。这里有人看到我的代码有问题吗?

非常感激!

4

2 回答 2

3

首先,您需要在 DOM 准备好时运行您的代码,为此,请将您的代码包装在一个就绪处理程序中:$(function() { ... }. 其次,最好检查valueselect 而不是selectedIndex,以防将来选项的顺序发生变化。

<script type="text/javascript">
    $(function() {
        $("#ddlSq1").change(function () {
            if ($(this).val() == "SQ6")
                $("#customSecurity").css("visibility", "visible");
        });
    });
</script>   
于 2012-05-17T12:56:43.943 回答
0

将此代码移动到 $(document).ready()

<script type="text/javascript">      
$(document).ready(function(){   
$("#ddlSq1").change(function () {             
if ($(this).attr('selectedIndex') == 5)                
$("#customSecurity").css("visibility", "visible");         
});     
});
</script>  
于 2012-05-17T12:57:28.893 回答