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>
2
  • use getParameterValues("countries"), btw that [] is not needed in java it's a php thing Commented Mar 31, 2016 at 11:06
  • awesome. Thanks for the []-clarification. Commented Mar 31, 2016 at 11:43

2 Answers 2

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)
     ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you too. this was very helpful!
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);        
      }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.