[英]Create JS array from input field values
I have x number of input fields with class='agency_field'. 我有x个输入字段,其中class ='agency_field'。 How can I create a JS array that contain the values of all fields with this class?
如何创建一个包含此类所有字段值的JS数组?
Using jQuery, this gives a syntax error: 使用jQuery,这会产生语法错误:
$(".agency_field").each(function(index) { agencies[] = $(this).val(); });
$(“。agency_field”)。each(function(index){agencies [] = $(this).val();});
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? 你已经习惯了像php这样的语言? ;) In Javascript, you'd use array.push() for appending to an array;
;)在Javascript中,您将使用array.push()附加到数组; so
所以
$(".agency_field").each(function(index) { agencies.push( $(this).val() ); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.