How to keep Dropdownlist value same after refresh the page How to keep Dropdownlist value same after refresh the page database database

How to keep Dropdownlist value same after refresh the page


<input type="hidden" name="selectedValue" value="0"/>  

put the above one in just below of your select tag

and do this in your servlet

String selectedValue = `request.getParameter("selectedValue")` 

now set the selectedValue into the servlet request

create a JS function in your final jsp

function selectedValue(){      var value =<%=request.getParameter("selectedValue")%>;      if(value !=null)          {        document.f1.slvalue.selectedIndex=value ;                  }    } 

call the selectedValue() function on bodyload of your final jsp page. "slvalue" is a name of your select tag


HTML CODE

<input type=hidden id ="selection" name="selection" value=""><select name="cate">  <option onclick="document.getElementById('selection').value='h';" value="h">India</option>  <option onclick="document.getElementById('selection').value='m';" value="m">USA</option>  <option onclick="document.getElementById('selection').value='c';" value="c">England</option></select>

JSP CODE

<%  String selected = request.getParameter("selection");%>

Now when you are on the JSP page you have an indication of what the user selected.When you render the element append the select attribute to the selected option

eg: < option value="h" selected > India < / option >

UPDATEIn the place where you display the dropdown you have to do some kind of validation where you need to check the selection value and what you are actually printing.

if(selected ==null || selected.equals('')){    //do regular printing of the dropdown as you do now}else{  out.print("<select>");  while(rs.next()){    if(rs.getString("VALUE").equals(selected )){        out.print("<option value=\""+rs.getString("VALUE")+"\" SELECTED >"+rs.getString("COUNTRY")+"</option>");    }else{        out.print("<option value=\""+rs.getString("VALUE")+"\" >"+rs.getString("COUNTRY")+"</option>");    }  }  out.print("</select>");}

PS: The code is written on the fly and could need some exception handling or some typos may exist


You can add selected to an <option> tag so that it's the initially selected value for the page.

<option value="h" selected>India</option>

would select the India option when the page loads.

You'll need to add some logic to your JSP to add selected to the correct <option> tag depending on the value that was selected when the page was submitted.