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()
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With