简体   繁体   中英

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

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(","));
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最终会包含你想要的东西。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM