Alwayz Change
Alwayz Change

Reputation: 225

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

Upvotes: 10

Views: 47529

Answers (3)

Graham
Graham

Reputation: 15214

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

Upvotes: 8

Jochem
Jochem

Reputation: 2994

Or use jQuery's map function:

$("div input[name='items[]']").map( function() { return $(this).val(); } ).get();

Upvotes: 4

Igor Dymov
Igor Dymov

Reputation: 16460

var values = [];
$("input[name='items[]']").each(function() {
    values.push($(this).val());
});

Upvotes: 38

Related Questions