Susie Susie - 1 year ago 52
HTML Question

Keep the radio button selected after refreshing the page or submitting the request

I understand this question may sound very basic but I have been trying to solve it this whole morning and I still haven't been able to do it. I will really appreciate any help.

I have two radio buttons in my jsp page. When either one is selected, it calls a javascript function. What evetually happens is if you select radio button 1, it displays data from table 1, if radio button 2 is selected, then data from table 2 is displayed.

As a result, my page gets refreshed and the radio buttons are not selected anymore. I would like to show the user which radio button was selected.

function viewUploadedData(){
document.location.href = "";

function viewTopsData(radio){
document.location.href = "";


<input type="radio" name="dataTypeToView" id="topsData" onclick="viewTopsData();"/>
<label for="topsData">TOPS Data</label><br/>
<input type="radio" name="dataTypeToView" id="uploadedData" onclick="viewUploadedData();"/>
<label for="uploadedData">Uploaded Data </label>

Answer Source

If you generate the html for a radio button using the "checked" attribute, it will be checked. For example, the following html will generate a radio button that is checked:

<input type=radio name=myradio value=1 checked>

So, having said that, you need to modify your jsp to conditionally generate the "checked" attribute for the appropriate radio button. Presumably your jsp knows which radio button was checked, so hopefully this should be easy to code.

So, you jsp code might look something like this:

String whichRadio = request.getParameter("myradio");
String r1checked = "";
if (whichRadio.equals("1")) r1checked = " checked";
String r2checked = "";
if (whichRadio.equals("2")) r2checked = " checked";
<input type=radio name=myradio value="1"<%= r1Checked %>>
<input type=radio name=myradio value="2"<%= r2Checked %>>

The above code will generate the checked attribute for whichever radio was checked when your jsp was called. If no radio was checked, then no checked attribute will be generated.