Matthew
Matthew

Reputation: 7735

Put multiple values from elements into array

A common situation is where I'll need to put values from multiple inputs into an array. Is there a one-liner, or simpler method, that can accomplish this?

var array = [];
$(".foo").each(function(){
    array.push($(this).val());
});

I'm imagining something like this:

 var array = $(".foo").getEach('val');

Upvotes: 0

Views: 45

Answers (1)

adeneo
adeneo

Reputation: 318372

Something like this is probably as close as you'll get without creating your own method

var array = $.map( $(".foo"), function(el){
    return el.value;
});

You could roll your own

$.fn.getEach = function(prop) {
    return $.map(this, function(el) {return $(el).attr(prop); })
}

to be called as

var array = $(".foo").getEach('value');

Upvotes: 2

Related Questions