I have a jQuery object obj
that encapsulates a set of input elements.
I am using this code in order to make an array out of each element's value :
$.map(obj, function(elem, i){
return $(elem).val();
});
The problem is that sometimes some of the input fields contain invalid values and i would like to skip them in the process of creating the array. Doing a simple return false
doesn't seem to skip the element but instead inserts a false
in the array.
I would like to know if there is a way to actually do that without using .each
explicitly.
Since it's an jQuery collection, you can execute .map
directly and then use .get
so that it becomes an array.
var values = obj.map(function(){
return this.value ? this.value : null;
}).get();
Note: The above check will return any value that isn't falsey.
See test case on jsFiddle.
I should have tried returning nothing (void) that did the trick, don't know why this didn't come across my head earlier.
In case you want to do the same, here is the fix:
$.map(obj, function(elem, i){
if($(elem).val().length == 0) return;
return $(elem).val();
});
EDIT
I just tested the length here and omitted to the validation code in order stay on the same subject
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