0

I have a website with select forms and am trying to make it work so that when a form is submitted, the select form retains what the user chose. I need to use JSP with servlet or Javascript.

<form method="post" id="mainForm" name="mainForm">
<div>
    <label style="margin-left: 10px;" for="specialty">Specialty:</label>
    <select name="specialty">
        <option value="ob/gyn">OB/GYN</option>
        <option value="surgeon">Surgeon</option>
        <option value="heart surgeon">Heart Surgeon</option>            
        <option value="pediatrician">Pediatrician</option>
        <option value="general physician">General Physician</option>
    </select>
</div>
<div>
    <label style="margin-left: 10px;" for="zipCode">ZIP Code:</label>
    <input type="text" name="zipCode" value=<%=patient.getZip().substring(0, 5) %>>
</div>
<div>
    <label style="margin-left: 10px;" for="range">Range From ZIP Code: </label>
    <select name="range">
        <option value="5">Exact (Match all 5 digits)</option>
        <option value="4">Match first 4 digits</option>
        <option value="3">Match first 3 digits</option>         
        <option value="2">Match first 2 digits</option>
        <option value="1">Far (Match only first digit)</option>
    </select>
</div>
<input type="submit" name="findExpert" value="Find Expert" />

What would I have to add to make this work?

1 Answers1

0

You probably want to be using something like Struts here. But the the slightly ugly, quick way to do it is this (assuming this JSP submits to itself, which it looks like it does): first, add this before the opening form tag:

<%
String specialty=request.getParameter("specialty");
String range=request.getParameter("range");
specialty=(specialty==null?"":specialty); // will be null if form not submitted yet
range=(range==null?"":range); // will also be null if not submitted yet
%>

Then, to take your first menu as an example, do this for every option tag:

<option value="ob/gyn" <%=specialty.equals("ob/gyn")?"selected=\"selected\"":""%>>OB/GYN</option>

That will work. There are JavaScript solutions which would work too, but they wouldn't be any easier to implement. Note again, though: unless this JSP is a one-off quicky just to get the job done, you'll end up with lots of messy code unless you use a framework (again, Struts is one possibility) that handles a lot of this stuff for you.

Steve Schneider
  • 392
  • 2
  • 5