Setting multivalued parameter in javascript

When I submit the form in HTML, I can pass the parameter multiple times, eg.

<input type="hidden" name="id" value="2">
<input type="hidden" name="id" value="4">

      

Then in struts I can have a bean with a String [] id property and it will fill the array correctly.

My question is, how can I do this 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 at the end of Struts, I just get a singleton array i.e. The string "2.4".

I must add, I need to submit this on a form, so I cannot just create a GET request, eg. ID = 2 &. ID = 4

+1


source to share


4 answers


Is this what you are looking for? It generates a hidden form field for each element of the 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);
}

      

+2


source


Not bad what you are trying to do, but here:

var inputs = document.getElementsByName('id');
for(var i=0; i<inputs.length; i++) {
    var input = inputs[i];
    input.value = myArray[i];
}

      



This iterates over all inputs named " id

" and assigns the appropriate value from myArray.

You better be sure myArray.length == document.getElementsByName('id').length

+2


source


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];

      

+1


source


forms[0].elements.theName

contains collections of all elements with the 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>

      

+1


source







All Articles