krerkkil
krerkkil

Reputation: 45

Set the default value of a Drop Down Menu based on data passed in to request

I'm trying to set the default value for a drop down menu based on information passed into the page. So far I have this:

<td>
    <select id="typeDropdown" name="typeDropdown">
        <option value="val1" selected="selected">Value 1</option>
        <option value="val2">Value 2</option>
    </select>
</td>

And that will always have the first value selected.

However, can I do something like this to set the default based on information given to the webpage?

<c:if test="${not empty data}">
    <c:set var="val" value="${data}" />
</c:if>
<td>
    <select id="typeDropdown" name="typeDropdown">
        <option value="val1" <c:if test="val eq 1">selected="selected</c:if> >Value 1</option>
        <option value="val2" <c:if test="val eq 2">selected="selected</c:if> >Value 2</option>
    </select>
</td>

where data is passed into the page as part of the request. I understand that the syntax is probably wrong, but I'm more interested in whether not the idea is sound.

EDIT 1:

So that didnt work. I received the following exception for my efforts:

org.apache.jasper.JasperException: An exception occurred processing JSP page /newInterface.jsp at line 127

124: <td>Field 1:</td>
125:    <td><select name="field1">
126:        <c:set var="tet" value="val1"/>
127:        <option value="val1" <c:if test="${old.val eq tet}">selected="selected"</c:if>>val1</option>
128:        <option value="val2">val2</option>
129:    </select>
130: </td>


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)

old.val is, for all intents and purposes, the same as that "val" variable from my initial idea.

Upvotes: 2

Views: 6736

Answers (1)

vector
vector

Reputation: 7576

1:
... the idea is ok though, first get the data value output, then move on to the select, parsing errors can be cryptic so why not edit the question and add the error

2: so make sure you can output that first as well, that might be why your 'if' blows up

Upvotes: 1

Related Questions