Search code examples
htmljspselectdropdownbox

Set the default selection for a dropdown


<tr>
    <td class="label">
    Filter:
    </td>
    <td>
    <select name="colSearchName" id="colSearchNameID" value="1">
    <%
        colNameIter = content.columnNameIterator( );
        for ( int i = 0; colNameIter.hasNext( ); ++i ) {
    %>
    <option value="<%= i %>"><%= colNameIter.next( ) %></option>
    <%
        }
    %>
    </select>
    </td>
    <td>
    <input id="autocompleteinput" type=text name="keyword" onKeyUp="autoCompleteOnTable(this.value);">
    </td>
</tr>

The above code is a dropdown box in which the values are dynamically selected from the XML file. The <option> with a value of 1 should be selected by default but it uses the <option> with a value of 0 instead. Setting the value of the <select> element doesn't help.


Solution

  • That's not how you set the selected item. You need to add the selected attribute to the <option> that you want selected.

    For example:

    <select name="colSearchName" id="colSearchNameID">
    <%
        colNameIter = content.columnNameIterator( );
        for ( int i = 0; colNameIter.hasNext( ); ++i ) {
            if (i == 1) {
    %>
    <option value="<%= i %>" selected><%= colNameIter.next( ) %></option>
    <%
            } else {
    %>
    <option value="<%= i %>"><%= colNameIter.next( ) %></option>
    <%
            }
        }
    %>
    </select>