0

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');

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

2 Comments

var array = $.map( $(".foo"), function(el){ return el.value; }); one-liner! [+1ed]
Or var arr = $('foo').map(function() { return this.value; }).get();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.