Setting a multi-valued parameter in javascript
-
08-07-2019 - |
Question
When I submit a form in HTML, I can pass a parameter multiple times, e.g.
<input type="hidden" name="id" value="2">
<input type="hidden" name="id" value="4">
Then in struts I can have a bean with property String[] id, and it'll populate the array correctly.
My question is, how can I do that in Javascript? When I have an array, and I set form.id.value = myArray, it just sets the value to a comma-separated list. So then on the Struts end, I just get one-element array, i.e. the String "2,4".
I should add, I need to submit this in a form, so I can't just generate a GET request, e.g. id=2&id=4.
Solution
Is this what you're looking for? It generates a hidden form field for each element of a JavaScript array:
var el;
for (var i = 0; i < myArray.length) {
el = document.createElement("input");
el.type = "hidden";
el.name = "id";
el.value = myArray[i];
// Optional: give each input an id so they can easily be accessed individually:
el.id = "hidden-myArray-" + i;
// Optional: give all inputs a class so they can easily be accessed as a group:
el.className = "hidden-myArray";
form.appendChild(el);
}
OTHER TIPS
Not positive what you're trying to do but here's a go:
var inputs = document.getElementsByName('id');
for(var i=0; i<inputs.length; i++) {
var input = inputs[i];
input.value = myArray[i];
}
That iterates over all the inputs with name 'id
' and assigns the corresponding value from myArray.
You better be sure myArray.length == document.getElementsByName('id').length
One approach would be to give each input a unique ID:-
<input id="id1" type="hidden" name="id" value="2">
<input id="id2" type="hidden" name="id" value="4">
Then in javascript:-
document.getElementById("id1").value = myArray[0];
document.getElementById("id2").value = myArray[1];
forms[0].elements.theName
contains a collections of all elements with name-attribute 'theName'. Example:
<form>
<input type="text" name="test"><br>
<input type="text" name="test">
</form>
<script>
var values = ['foo', 'bar'];
var testElements = document.forms[0].elements.test;
for(var i = 0; i < testElements.length; ++i)
testElements[i].value = values[i];
</script>