Search code examples
javajspsessioncheckboxscriptlet

error submitting multiple checkboxes


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"


Solution

  • 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);
        }