Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get values of input element with the same name as an javascript array?

I want to get values of the input element that those elements are under the same name, name="items[]"
for example:

<div>...<input type="text" name="items[]" value="1" /></div>
<div>...<input type="text" name="items[]" value="2" /></div>
<div>...<input type="text" name="items[]" value="3" /></div>

And I wish to get the result something like:

[1, 2, 3] //that store in an javascript variable.

Do I need to do a loop to access all the elements to get its value? Please give me a good solution either javascript or JQuery.
Thanks

like image 363
Alwayz Change Avatar asked Aug 23 '11 07:08

Alwayz Change


People also ask

How do you input an array in JavaScript?

var input = document. getElementsByName('array[]'); The document. getElementsByName() method is used to return all the values stored under a particular name and thus making input variable an array indexed from 0 to number of inputs.

How do I find an element in an array of arrays?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


3 Answers

var values = [];
$("input[name='items[]']").each(function() {
    values.push($(this).val());
});
like image 78
Igor Dymov Avatar answered Sep 29 '22 17:09

Igor Dymov


JavaScript only:

var values = [];
var fields = document.getElementsByName("items[]");
for(var i = 0; i < fields.length; i++) {
    values.push(fields[i].value);
}

Warning, see: getElementsByName in IE7

like image 28
Graham Avatar answered Sep 29 '22 17:09

Graham


Or use jQuery's map function:

$("div input[name='items[]']").map( function() { return $(this).val(); } ).get();
like image 35
Jochem Avatar answered Sep 29 '22 16:09

Jochem