3

I have some hidden inputs that are generated dynamically using JQuery. For example :

<input type="hidden" name="name1" value="SomeValue1">
<input type="hidden" name="name2" value="SomeValue2">

The method

FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("name1") 

returns the value SomeValue1 which is correct. But, at runtime I am not aware of the input names. How can I get all the hidden inputs without knowing their names ?

Thansk for help.

Tarik
  • 4,961
  • 3
  • 36
  • 67
MadNeox
  • 2,453
  • 3
  • 15
  • 26

1 Answers1

4

Give them all the same name, so that you can use getRequestParameterValuesMap() instead.

<input type="hidden" name="name" value="SomeValue1">
<input type="hidden" name="name" value="SomeValue2">
...
String[] names = externalContext.getRequestParameterValuesMap().get("name");

The ordering is guaranteed to be the same as in HTML DOM.

Alternatively, based on the incremental integer suffix as you've in the HTML DOM, you could also just get the request parameter in a loop until null is returned.

List<String> names = new ArrayList<>();

for (int i = 1; i < Integer.MAX_VALUE; i++) {
    String name = requestParameterMap.get("name" + i);

    if (name != null) {
        names.add(name);
    } else {
        break;
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • @BalusC just for my curiosity, I am not so familiar with HTML, but I don't understand why we can add inputs whith same ID while its not possible in JSF? and also you said `requestParameterMap.get("name" + i);`, when that `i` is generated ? thanks in advance – Tarik Feb 17 '15 at 14:44
  • @Tarik: `id` != `name`. As to `i`, that's in OP's case done by jQuery. – BalusC Feb 17 '15 at 14:45
  • @BalusC Oh! I think I was confused because in the generated HTML of my JSF pages the name is always (I guess) the same as the id, is that always true ? – Tarik Feb 17 '15 at 14:51
  • 1
    @Tarik: Not for `UISelectMany` components (e.g. multi-select checkbox/menu). See also a.o. http://stackoverflow.com/questions/1928675/servletrequest-getparametermap-returns-mapstring-string-and-servletreques/ for a basic JSP/servlet based answer. – BalusC Feb 17 '15 at 14:53