Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Hidden Input Array

Is it possible to have the value of a hidden input field as an array and then have it passed to the Spring MVC controller?

function foo(){
    var myArray = new Array();
    myArray[0] = "Hello";
    myArray[1] = "World!";
    document.getElementById("hiddenInp").value=myArray;
}

And then in the controller do something like

@RequestMapping ...
public String test(HttpServletRequest request)
{
    String[] myArray = request.getParameter("hiddenInp");
    // Assuming that the name of the hidden input field is also hiddenInp
    System.out.println(myArray[0] + myArray[1]);
    ...
}

How about if I am working with an associative array? Where the indices are string rather than int

like image 391
szrrizvi Avatar asked Jun 07 '12 21:06

szrrizvi


2 Answers

Your best option would be to stringify the array and then assign it.

element.value = JSON.stringify( ["Hello", "World"] );

The resulting value will be a JSON string that can then be parsed on the server, recreating the array. This approach works for objects as well if you wish to have something resembling an associative array.

I should note that while JSON has fairly good support across browsers today, older browsers may not support it. You can polyfill the feature fairly easily in those cases:

like image 104
Sampson Avatar answered Sep 24 '22 16:09

Sampson


You can only pass a string as a parameter, as well as to an input's value. That means you Array will automatically be converted to a string by joining it with ";", you could do that manually with the .join() method, too.

Serverside you then will need to split that string by the chosen delimiter.

If you want to send them as an array, afaik you will need two input elements:

<input type="hidden" name="hiddenInp[]"<!-- should be more descriptive --> value="a" />
<input type="hidden" name="hiddenInp[]"<!-- the same name --> value="b" />
like image 25
Bergi Avatar answered Sep 24 '22 16:09

Bergi