How to get input element values ​​with the same name as javascript array?

I want to get the values ​​of the input element so that these elements are under the same name, name = "items []"
eg:

<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 want to get the result something like this:

 [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 to either javascript or jQuery.
Thanks

+4
source share
3 answers
 var values = []; $("input[name='items[]']").each(function() { values.push($(this).val()); }); 
+24
source

Or use the jQuery display function:

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

JavaScript only:

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

Warning: getElementsByName in IE7

+1
source

All Articles