Link to home
Start Free TrialLog in
Avatar of dekathari
dekathari

asked on

Retain selected value in combo box after page getting refreshed

I have a jsp with a combo box with these options.

<select name="category">
            <option value="Shopping">Shopping</option>
            <option value="Sports" >Sports</option>
            <option value="Travel">Travel</option>
            </select>

After I select any of these options, I need to refresh the page, but the problem is that the selection is not getting saved after refrsh.  How do I retain the selection after refresh?  

ASKER CERTIFIED SOLUTION
Avatar of Manish
Manish
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
%
if(category.equals("Shopping")){ %>
<option value="Shopping" selected>Shopping</option>
<% } else {%>
<option value="Shopping">Shopping</option>
<%} %>
Avatar of dekathari
dekathari

ASKER

This is what I tried,  but I am getting an exception

Duplicate local variable category

If I change the category variable to some other name, the error is gone, but the selecttion is not retained. Am I missingg something?

<select name="category" onChange="myForm.submit();">
            <option value="Shopping">Shopping</option>
            <option value="Sports" >Sports</option>
            <option value="Travel">Travel</option>
             </select>
             
             <%

              String category=request.getParameter("category");
             if(category.equals("Shopping")){ %>
            <option value="Shopping" selected>Shopping</option>
              <% } else {%>
          <option value="Shopping">Shopping</option>
          <%}
        %>
         
Thanks a lot.

I have found the solution, this is what I did and is working fine.

<script>
function messageValue()
{
 
  document.myForm.submit();
}
 </script>

<%
String selected = (String)request.getParameter("category");
  if(selected == null)
     selected = "Shopping";   // default value
%>


<select name="category" onchange="messageValue()">
             <option value="Shopping" <%=selected.equals("Shopping")?"selected":""%> > Shopping</option>
             <option value="Sports" <%=selected.equals("Sports")?"selected":""%> > Sports</option>
            <option value="Travel" <%=selected.equals("Travel")?"selected":""%> > Travel</option>
</select>