最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create JS array from input field values - Stack Overflow

programmeradmin4浏览0评论

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:

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

Share Improve this question asked Apr 5, 2011 at 13:15 stefstef 27.8k31 gold badges107 silver badges143 bronze badges 22
  • 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
 |  Show 17 more ments

7 Answers 7

Reset to default 10

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 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() ); });
发布评论

评论列表(0)

  1. 暂无评论