views:

1473

answers:

3

Let's say i have a jsp page which contains a dropdownlist. when user select a item and click submit to submit the JSP page to itself, after that , the JSP page will reload and item selected before will disselected. How can i make it not change even after reload the JSP page?

A: 

Set the selected attribute of the option that was passed in to the form... your output should look like this (assuming the user selected "Saab"):

<select>
  <option>Volvo</option>
  <option selected="selected">Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</select>
beggs
I think this is not work, how can we know which option the user selected ? if use this method, i think i should write such kind of code:<%if(volov)%><option selected="selected">Volvo</option><%if(saab)%>......I think this is not the right method. could you give me sample code ?
MemoryLeak
It's the same answer as all the others... Just with less code. The `select` element should be within a form and have an id (it does not in the example) when the page POSTs back to the JSP the id and the value of the selected `option` element will be passed to the form. As you iterate over of the elements to output the form you need to test if each option's value is equal to the value passed in to the POST.
beggs
+1  A: 

You have to re-select it.

So it will end up like this:

 <select name="dropdown">
 <%
       String selectedItem = request.getParameter("dropdown");
       for( String item : values ) {
 %>
       <option <%=item.equals(selectedItem)?selected:""%>><%=item%>

 <%
       }
 %>

That way each time you reload the jsp page, you verify if the current item you're painting is the same it was previously selected by the user. If so, you append "selected" to the option ( the first time it won't match anything )

I'm a bit rusty in JSP, so , probably there is a more "elegant" way to do it, but this "old-style" does works for sure.

I hope it helps.

OscarRyz
A: 

I think this method is better:

<script type = "text/javascript"/>
<%String selectedItem ;
if(request.getAttribute("dropdown") != null){
  selected= request.getAttribute("dropdown");%>

document.getElementById("selectbox").selectedIndex = selectedItem;
<%}%>
</script>

I think this method will work.

MemoryLeak
That's what I said... I didn't say how to do it... this should work.
beggs