stef
stef

Reputation: 27749

Create JS array from input field values

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(); });

Upvotes: 4

Views: 7553

Answers (7)

karim79
karim79

Reputation: 342635

You 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(","));

Upvotes: 10

Paul
Paul

Reputation: 2157

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() ); });

Upvotes: 0

McStretch
McStretch

Reputation: 20645

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()) });

Upvotes: 0

Chandu
Chandu

Reputation: 82913

Your code shd be slightly changed to:

var agencies = [];
$(".agency_field").each(function(index) { 
    agencies.push($(this).val()); 
});

Upvotes: 0

zindel
zindel

Reputation: 1865

var arr = []; $(".agency_field").each(function(index) { arr.push($(this).val()); });

arr would contain what you want in the end.

Upvotes: 0

StrixVaria
StrixVaria

Reputation: 714

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.

Upvotes: 0

Alex
Alex

Reputation: 2122

var agencies = [];
$(".agency_field").each(function(index) { agencies.push($(this).val()); });

Upvotes: 0

Related Questions