10

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

Alwayz Change
  • 225
  • 1
  • 4
  • 13

3 Answers3

38
var values = [];
$("input[name='items[]']").each(function() {
    values.push($(this).val());
});
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
8

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

Community
  • 1
  • 1
Graham
  • 14,885
  • 4
  • 36
  • 42
4

Or use jQuery's map function:

$("div input[name='items[]']").map( function() { return $(this).val(); } ).get();
Jochem
  • 2,995
  • 16
  • 18
  • 2
    Be careful with .map(), in some browsers it returns an array but in others it returns an object `m.fn.init[]` (Chrome). This latter one cannot be stringified by JSON.stringify(). Specifically, the following two are NOT equivalent: `var arr=$('input[name="foo"]').map(function(){return this.value}).get()` with `var arr=[]; $('input[name="foo"]').each(function(){arr.push(this.value)})`. In the first case `arr` is not an Array whereas in the latter case it is. `JSON.stringify(arr)` fails for the former, but works for the latter. – Normadize Apr 08 '15 at 16:13