I need a jQuery filter/map/each type function to check if ALL elements satisfy a condition:
function areAllValid(inputs){
return $.someFunction(inputs,
You don't need to use jQuery to do this. You can do this in native JavaScript using Array.prototype.every, which is supported in IE 9+.
function areAllValid(inputs){
return inputs.every(function(input) { return input.length > 0; });
}
If you are using EcmaScript 2015, you can tidy it up further:
var areAllValid = inputs => inputs.every(input => input.length > 0);
There are some minor optimization issues unaddressed by the existing answers, so I'll throw my hat in the ring with what I believe is the most readable/performant code.
Add a jQuery extension method like this which will short circuit :
/**
* Determines whether all elements of a sequence satisfy a condition.
* @@param {function} predicate - A function to test each element for a condition.
* @@return {boolean} true if every element of the source sequence passes the test in the specified predicate
*/
$.fn.all = function (predicate) {
$(this).each(function (i, el) {
if (!predicate.call(this, i, el)) return false;
});
// we made it this far, we're good.
return true;
};
Then call it like this:
var allValid = $("form :input").all(function () {
return $(this).valid();
});
function areAllValid(inputs){
return Array.prototype.every.call(inputs, function(input) { return input.length > 0; });
}
This will go through each item, AND the condition with the previous result, so that it will only return true if the condition is true for all items. You could of course replace the condition with a callback function, and do inputs.each(
instead of $('input')
but you may need to adjust the code a bit depending on whether inputs is a jquery object or not.
var all = true;
$('input').each( function(index, value) {
all = all & ($(value).val().length > 0);
});
return all;
I usually use following form to get matches in JQuery
$.map($("[some selector]"), function(e) {
return ([some matching mechanism]);
}).indexOf(false) == -1;
In your specific case it would look like this:
$.map(inputs, function(e) {
return (e.length > 0);
}).indexOf(false) == -1;
Hope this saves you some time.
The answer is YES, it has a method grep that can meet your requirement. For example:
inputs= jQuery.grep(inputs, function(input){
return input.length>0;
});
if(inputs.length>0) return true;
return false;
I don't test it, maybe it has tiny issue but should be almost like this.