Alex Ironside
Alex Ironside

Reputation: 5049

Setting a selected value in dropdown menu

I'm building a panel for a user to update their information. So far I figured out how to put the information like this:

<div class="form-group row">
    <label for="fullName" class="col-sm-2 col-form-label">Full Name</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" id="fullName" name="fullName" value="<%= u.fullName %>"
               required>
    </div>
</div>

u is the current user.

But how can I do it in this case?

<div class="col-sm-4">
    <!-- <input type="text" class="form-control" id="ageGroup" required > -->
    <select id="ageGroup" name="ageGroup" class="form-control">
        <option value="">Choose...</option>
        <option value="18 - 24">18 - 24</option>
        <option value="25 - 29">25 - 29</option>
        <option value="30 - 34">30 - 34</option>
        <option value="35 - 44">35 - 44</option>
        <option value="44 - 54">44 - 54</option>
        <option value="55 - 64">55 - 64</option>
        <option value="65 +">65 +</option>
    </select>
</div>

Preferably without writing 8 if statements?

I'm using ejs template system.

Upvotes: 1

Views: 47

Answers (1)

Ignacio Ara
Ignacio Ara

Reputation: 2582

Using a loop? for example:

<select id="ageGroup" name="ageGroup" class="form-control">

<%
var options = [ "18-24", "25-29", "30-34", "35-44", "44-54", "55-64", "65+" ];
for ( var i = 0; i < options.length; i++ )
{
    var selected = ( config[0].volume == i ) ? "selected" : "";
    %><option value="<%=options[ i ] %>" <%=selected %>><%=i %></option><%
}
%>
</select>

Upvotes: 1

Related Questions