Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

val() loop possibilities opposed to each() [duplicate]

So a bit of a hypothetical question (and don't hesitate to let me know if there is another post with the same question - I didn't find one though)

So, the .val() method returns the current value of the first element matched by the selector. Is there another "shorthand" jquery method that get's the value of all matched elements and returns an array?

Or am I safest just doing this:

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

As I said above, I looked for something, but it might just be that I have to use .each()

like image 573
Toiletduck Avatar asked Jul 18 '13 21:07

Toiletduck


1 Answers

No, there's no shorthand. However, there is a shorter method than yours:

var myResult = $(".myClass").map(function(){
    return this.value;
}).get();

and if you really wanted to, you could create your own shorthand:

$.fn.getValAsArray = function(){
    return this.map(function(){ return this.value; }).get();
};

var myResult = $(".myClass").getValAsArray();

a few more alternatives:

$.map

var myResult = $.map($.makeArray($(".myClass")),function(input){
    return input.value;
});
// or
var myResult = $.map($(".myClass").get(),function(input){
    return input.value;
});

[].map

var myResult = $.makeArray($(".myClass")).map(function(input){
    return input.value;
});
// or
var myResult = $(".myClass").get().map(function(input){
    return input.value;
});
like image 66
2 revs Avatar answered Sep 27 '22 16:09

2 revs