Javascript Hidden Input Array
Asked Answered
M

4

11

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

Maurinemaurise answered 7/6, 2012 at 21:3 Comment(5)
JavaScript doesn't have associative arrays.Vagus
@JonathanSampson Maybe I'm using the wrong term. I meant, instead of index such as "0" and "1", I do myArray["A"] = "Hello";. I know that works because I've tried alert(myArray["A"]) and it gives me the pop-up box with "Hello".Maurinemaurise
@JonathanSampson: But objects can be (and are) used as maps...Unknot
@Unknot Yes; objects can have keys, but they're not associative arrays. One big difference is the order of values. With an array the order is fixed; not so with objects and their properties.Vagus
@Maurinemaurise You're referring to an object: var myArray = { 'A' : 'Hello' };.Vagus
V
19

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:

Vagus answered 7/6, 2012 at 21:6 Comment(6)
not necessary to do. setting the value as an array will do exactly what .join() does. using .join() is just extra processing for nothing.Octet
@ianpgall Noted. I tend to forget that JavaScript will automatically handle the casting of an array to the appropriate type and value.Vagus
i hadn't expected it to work - i thought it might include "[" and "]" but it ended up working like .join() anyways. no problem, just wanted to point it out!Octet
How about if I have an associative array? Where the indicies are string rather then numbers.Maurinemaurise
@ianpgall - Is .join() really extra processing though? If the value you set is already a string JS doesn't have to convert it, so it's not like it processes it twice. Plus of course .join() gives you explicit control over the joining character(s).Decoteau
it's not exactly "extra" processing...especially something the user would never notice. so you're right, if you want to control the character the delimits the string, you should use .join(). but to me, it doesn't make sense to use it if you're okay with "," being the delimiter, because using .value=[1, 2, 3] will convert the array to the value "1,2,3" which is exactly what you want.Octet
U
2

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" />
Unknot answered 7/6, 2012 at 21:12 Comment(3)
you can set an input's value as an array. javascript basically does what .join() WOULD do, but it's not necessary to use .join() unless you want a delimiter other than ","Octet
That's exactly what I said. However, I would even use .join(",") to make it clear that I'm setting a string.Unknot
I like this "multiple hidden fields" solution most, it behaves like a multiple select would and no further serialization oder deserialization is neededMoschatel
O
1

However you set it in Javascript, you'll have to parse it on the server. That probably means splitting the value by "," into a C# array, then accessing it as you want. All values sent in a form submission are sent as a string exactly as-is.

You might want to use http://www.w3schools.com/jsref/jsref_join.asp to set the value of the hidden input. It's not necessary though - it seems to be fine without using .join(). But it's important to remember that the value will be a string on the server, not an array.

Octet answered 7/6, 2012 at 21:6 Comment(1)
Yes, I saw that a long time ago. While I think that's funny, it has nothing to do with using w3 schools for simple references. I provided the link so the OP can use the syntax correctly, not as a solution (especially since I'm saying .join() shouldn't be used).Octet
G
1

I found the answer in via the following link.

When you want to assign any JavaScript Object or an Array do it as follows:

var javascript_variable = 'object' or ['fruit1', 'fruit2', 'fruit3'];
$( '#hiden_input_element_unique_id' ).val( JSON.stringify(javascript_variable) );

After form submission, in the serverside we have to decode it as follows:

$fruits_array = json_decode( $_POST['hiden_input_element_unique_name'] );

This way you can get any JavaScript array in the server-side, which you set it inside to a form element via JavaScript, in the client-side!

Gnarly answered 13/9, 2014 at 16:39 Comment(1)
@Flexo thanks for the guidance and the edit! Will follow that in the meantime! :-)Gnarly

© 2022 - 2024 — McMap. All rights reserved.