Abhishek
Abhishek

Reputation: 2034

How to set a default value in a dropdown javascript

I'm trying to bind a JSON object to a dropdown as:

JSON data

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

This is how I've binded the data in my 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>

It works perfectly but the problem is I've a selected dropdown item sent to me in the JSON as:

"userSecureQuestion": "Mother's Maiden Name"

and I want this to be selected by default instead of the first one. Please suggest what can be done here? Thanks in advance!

Upvotes: 0

Views: 1792

Answers (1)

Amadan
Amadan

Reputation: 198388

You would need to check in the loop whether the current text equals the default text, and add selected into the option if it is. I can't give you the code for it with any confidence since you did not tag the post with the template engine; but probably something like this might do:

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

Upvotes: 1

Related Questions