如何在下拉列表中设置默认值

时间:2015-11-17 02:00:47

标签: javascript jquery json html.dropdownlistfor

我试图将JSON对象绑定到下拉列表:

JSON数据

"securityQuestions": [
    "First Pet's Name",
    "City I was born in",
    "Mother's Maiden Name",
    "Favorite teacher's Name"
  ]

这就是我在HTML中绑定数据的方式:

<label>Security Question</label>
                <span class="select"><select class="form-control">
                    <% _.each(model.securityQuestions, function(val, text) { %>
                        <option val="<%=text%>"><%= val%></option>
                    <% }); %>
                </select></span>

它完美无缺,但问题是我在JSON中发送给我的选定下拉项目为:

"userSecureQuestion": "Mother's Maiden Name"

我希望默认选择此项而不是第一项。请建议可以在这做什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在循环中检查当前文本是否等于默认文本,如果是,则将selected添加到选项中。由于你没有用模板引擎标记帖子,我无法放心地给你代码。但可能会这样:

<option val="<%=text%>" <%= text === model.userSecureQuestion ? "selected" : "" %>><%= val%></option>