How to check radio button according to value retrieved from database?

anshulankush picture anshulankush · Mar 29, 2013 · Viewed 13.8k times · Source

I have a JSP page where I am saving a form and value of the selected radio button in database. Now , I need to update that page, everything is being displayed, but the radio button are not selected. I don't know how to show the previously selected radio button on my jsp. I am using Struts2, Java.

Jsp Code:

    <div id="patientCondition">
            <input type="radio" id="new" value="n" name="pSB.radioInnerSubjective" /><label for="new">New</label>
            <input type="radio" id="noChange" value="nC" name="pSB.radioInnerSubjective" /><label for="noChange">No Change</label> 
            <input type="radio" id="progressing" value="p" name="pSB.radioInnerSubjective" /><label for="progressing">Progressing</label>
            <input type="radio" id="notProgressing" value="nP" name="pSB.radioInnerSubjective" /><label for="notProgressing">Not Progressing</label>
    </div>

Suppose I get value of radio button as 'nC' from database, now how do i select second radio button automatically.

I tried:

<input type="radio" id="new" value="n" <s:if test="${patientSoapBean.radioInnerSubjective == 'n'}">CHECKED</s:if> name="patientSoapBean.radioInnerSubjective"/><label for="new">New</label>

But I am getting error:

Mar 28, 2013 6:07:54 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /WEB-INF/views/patient_soap.jsp (line: 703, column: 44) According to TLD or attribute directive in tag file, attribute test does not accept any expressions

Answer

Aleksandr M picture Aleksandr M · Mar 29, 2013

You cannot use ${...} inside Struts2 tags and you need to swap ' and " in test attribute to correctly compare with one character string.

<input type="radio" id="new" value="n" <s:if test='patientSoapBean.radioInnerSubjective == "n"'>checked</s:if> name="patientSoapBean.radioInnerSubjective"/>
<label for="new">New</label>

And of course you need getters/setters for patientSoapBean and radioInnerSubjective.

BTW Struts2 has <s:radio> tag which will check selected radio button.