Tea Ivanovic
Tea Ivanovic

Reputation: 21

How to dispaly values of two or more checkbox

I have this little form:

<form action="forma2.jsp" method="POST" target="_blank" >
        <input type="checkbox" name="fit" /> FIT</br>
        <input type="checkbox" name="fdu" /> FDU </br>
        <input type="checkbox" name="fam"/>FAM
    
        
        <input type="text" name="ime"/><br>           
        <input type="submit" value="Potvrdi" />
    </form>

And this little code to show me information about selected checkboxes:

<body>

    <% if (request.getParameter("fit") != null) { %>
    <p> Today is FIT</p><br>
    <% } else if (request.getParameter("fdu") != null) { %>
    <p> Today is not FDU</p><br>
    <% } else if (request.getParameter("fam") != null) { %>
      <p> Today is not FAM</p><br>
        <% } else { %>
        <p>Please choose one!</p>
    <% }%>
</body>

My problem is that I dont know how to make it so I can click on two checkboxes to get information not just only one. So if I selected checkbox number1 and checkbox number2 how to make so program display me information about both checkboxes.

Upvotes: 1

Views: 84

Answers (2)

Swati
Swati

Reputation: 28522

You can give same name to all checkboxes you have under your form tag and then use request.getParameterValues("chcks[]") to get values of all checkboxes . i.e:

Your jsp code :

 <form action="forma2.jsp" method="POST" target="_blank">
    <input type="checkbox" name="chcks[]" value="FIT"/>FIT
    <input type="checkbox" name="chcks[]" value="FDU"/>FDU
    <input type="checkbox" name="chcks[]" value="FAM"/>FAM
    <input type="text" name="ime"/><br>           
    <input type="submit" value="Potvrdi" />
  </form>

Then to get values from checkboxes do like below :

  if(request.getParameterValues("chcks[]")!=null){
        //get values of checkbox
        String[] datas = request.getParameterValues("chcks[]");
      //loop through values
        for(int i=0;i< datas.length;i++){
        //print
        out.println("Today is "+datas[i]);
        
        }
     }

Upvotes: 1

SevvyP
SevvyP

Reputation: 385

You have it set up as if/else if/else if. This will only choose 1 to display. You can fix this by changing each to an individual if statement.

Upvotes: 0

Related Questions