"Any" boolean function in jquery

Wilson picture Wilson · May 16, 2013 · Viewed 18.3k times · Source

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 of pseudo, not real jquery):

$('input.tb').any(val().length == 0);

Note: I know it could be done with a helper method, just curious if it was possible in one statement.

Answer

KyleMit picture KyleMit · Apr 7, 2017

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<this.length ; i++) {
     if (filter.call(this[i])) return true;
  }
  return false;
};

Then use it like this:

var someEmpty= $(":input").any(function() { 
    return this.value == '';
});

This yields much better perf results:

Performance Graph


If you do go the pure jQuery route, $.is(<sel>) is the same as !!$.filter(<sel>).length so it probably makes for shorter and more imperative code to use is instead of filter.

jQuery is Docs


Here's an example of $.any() in action:

jQuery.fn.any = function(filter){ 
  for (i=0 ; i<this.length ; i++) {
     if (filter.call(this[i])) return true;
  }
  return false;
};

$(function() {

  $(":input").change(function() {
  
    var someEmpty = $(":input").any(function() { 
        return this.value == '';
    });

    console.log("Some Empty:", someEmpty);


  }).eq(0).change(); // fire once on init

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" value="">
<input type="text" value="">
<input type="text" value="">

Further Reading: