I have x number of input fields with class='agency_field'. How can I create a JS array that contain the values of all fields with this class?
Using jQuery, this gives a syntax error:
$(".agency_field").each(function(index) { agencies[] = $(this).val(); });
I have x number of input fields with class='agency_field'. How can I create a JS array that contain the values of all fields with this class?
Using jQuery, this gives a syntax error:
Share Improve this question asked Apr 5, 2011 at 13:15 stefstef 27.8k31 gold badges107 silver badges143 bronze badges 22$(".agency_field").each(function(index) { agencies[] = $(this).val(); });
- Holy @#%# - you just got 6 answers within a minute of each other. – McStretch Commented Apr 5, 2011 at 13:19
- Hard to beat SO response times! – stef Commented Apr 5, 2011 at 13:20
- LOL Five each() answers, and only one map() answer... – Šime Vidas Commented Apr 5, 2011 at 13:23
- @Šime - I'm not sure how well-known map() is. each() is seen all over the place and it's easy to use (more familiarity). I gave this karim's answer +1 though because the documentation says map() is especially useful for this scenario. – McStretch Commented Apr 5, 2011 at 13:27
- That being said, where's the love for the each() answers? They're still acceptable answers, and more readable IMHO. – McStretch Commented Apr 5, 2011 at 13:30
7 Answers
Reset to default 10You can use .map
instead, which is perhaps more suited to your purpose:
var values = $(".agency_field").map(function() {
return this.value;
}).get();
alert(values.join(","));
var agencies = [];
$(".agency_field").each(function(index) { agencies.push($(this).val()); });
You're creating a new array for each iteration. Try instead instantiating an array before the each call and adding to the array each iteration.
var arr = []; $(".agency_field").each(function(index) { arr.push($(this).val()); });
arr
would contain what you want in the end.
Your code shd be slightly changed to:
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
You need to create an array initially and then add each value to that array:
var agencies = [];
$(".agency_field").each(function(index) { agencies.push($(this).val()) });
You're quite used to a language like php? ;) In Javascript, you'd use array.push() for appending to an array; so
$(".agency_field").each(function(index) { agencies.push( $(this).val() ); });