0

This question is the same as How to post multiple <input type="checkbox" /> as array in PHP?, but I can't make the solution work in my java servlet setup. When using the apporach of adding a [] to the name property of the grouped checkboxes, I only get the first checked option. I am not sure if it is the actual posted array that is containing only one element, or if I'm not accessing it right server side. Here is what I do to check the value in java:

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    for(String name : request.getParameterMap().keySet()){      
        System.out.println(name +": " + request.getParameter(name));        
    }
}

this prints countries[]: US, even if I have more checboxes checked after the US-input. the value changes after which checkbox is the first of the checked ones. What am I doing wrong?

Here is my HTML:

<form action="mypage" method="post">
    <input id="cb-country-gb" type="checkbox" name="countries[]" class="hide" value="GB"/>
    <input id="cb-country-us" type="checkbox" name="countries[]" class="hide" value="US"/>
    <input id="cb-country-ge" type="checkbox" name="countries[]" class="hide" value="GE"/>
    <input id="cb-country-es" type="checkbox" name="countries[]" class="hide" value="ES"/>
    <button type="submit" class="btn btn-primary">Search</button>
</form>
Community
  • 1
  • 1
jumps4fun
  • 3,994
  • 10
  • 50
  • 96

2 Answers2

2

If you check multiple checkboxes the request contains multiple parameters with name countries[].

If you call request.getParameter("countries[]") only the first parameter value is returned.

Instead you need to use

String[] checked = request.getParameterValues("countries[]");
if (checked != null)
     ...
wero
  • 32,544
  • 3
  • 59
  • 84
1

You should use [getParameterValues][1] that returns an array of String objects containing all of the values the given request parameter has :

Test that with following code:

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    for(String name : request.getParameterMap().keySet()){
      for(String value : request.getParameterValues(name)){
          System.out.println(name +": " + value);        
      }
    }
}
user987339
  • 10,519
  • 8
  • 40
  • 45