Is there any easy way to check if any elements in a jquery selector fulfill a condition? For instance, to check if any textboxes in a form are empty (kind o
The problem with the current answers and also jQuery's own filtering functions, including .is(), .has(), and .filter() is that none of them short circuit as soon as the criteria is met. This may or may not be a large performance concern depending on how many elements you need to evaluate.
Here's a simple extension method that iterates through a jQuery object and evaluates each element so we can early terminate as soon as we match the criteria.
jQuery.fn.any = function(filter){
for (i=0 ; i
Then use it like this:
var someEmpty= $(":input").any(function() {
return this.value == '';
});
This yields much better perf results:
If you do go the pure jQuery route, $.is( is the same as !!$.filter( so it probably makes for shorter and more imperative code to use is instead of filter.
$.any() in action:jQuery.fn.any = function(filter){
for (i=0 ; i