error submitting multiple checkboxes

127 views Asked by At

I am using this scriplet within my jsp:

<%
    String q3 = request.getParameter ("checkbox1");
    session.setAttribute("q3", q3);
%>

This will get the values from these checkboxes

<p> Which of the following are associated with Threading? Select two </p>
    <input type="checkbox" name="checkbox1" value="LiveLock">LiveLock<br>
    <input type="checkbox" name="checkbox1" value="Stack Overflow">Stack Overflow<br>
    <input type="checkbox" name="checkbox1" value="Heap">Heap<br>
    <input type="checkbox" name="checkbox1" value="Starvation">Starvation<br>
             <input type="submit" value="Next" >

Or rather..thats what it should do. But when i grab the values and print them out as so

<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose <%= session.getAttribute("q1") %> </p>
<p>For question 2 you chose <%= session.getAttribute("q2") %> </p>
<p>For question 3 you chose <%= session.getAttribute("q3") %> </p>
<p>For question 4 you chose <%= session.getAttribute("q4") %> </p>

The radio buttons for q1,2,4 work fine. the check box will only return the first value that is checked or rather. The value that comes first i.e. if i select "Heap" and then "Livelock", in the print outs it will display "LiveLock"

2

There are 2 answers

12
SpringLearner On BEST ANSWER

you should use request.getParameterValues() instead of request.getParameter() because checkbox names are same.

Remember that getParameterValues() returns array so you have to do

  String q3[] = request.getParameter ("checkbox1");

and for retrieving values iterate it like below

for(String s:q3)
{
System.out.println(s);
}

for printing in the browser

you can do

for(String s:q3)
    {
    out.println(s);
    }
2
AudioBubble On

Use request.getParameterValues to get multiple checkbox selection:

String[] q3 = request.getParameterValues ("checkbox1");

Store in session:

session.setAttribute("q3", request.getParameterValues("checkbox1"));

Traverse to display values:

<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose 
    <%String[] ans = (String[])session.getAttribute("q3");
    for(String chkd : ans) {
        out.print(chkd);
        out.print(", ");
    }%>
</p>

Note: use of scriplets are not recommended.