18

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.

Wilson
  • 8,270
  • 19
  • 62
  • 98

6 Answers6

17

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 (var 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 declarative code to use is instead of filter.

jQuery is Docs


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

jQuery.fn.any = function(filter){ 
  for (var 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:

KyleMit
  • 35,223
  • 60
  • 418
  • 600
12

jQuery has a lot of pseudo selectors built in: http://api.jquery.com/category/selectors/jquery-selector-extensions/

You can also build your own with the filter() function: http://api.jquery.com/filter/

$('input.tb').filter(function() { return this.value.length == 0});
Malk
  • 11,525
  • 4
  • 32
  • 32
8

.is() with a function argument is what you're after.

var anyEmpty = $('input.tb').is(function(index, element) {
    return !element.value;
})

WARNING:

This function is surprising in that it doesn't short circuit. It will needlessly iterate through all selected elements, even if the callback has already been satisfied.

let i = 0
let result = $('div').is((index, element) => {
  i++;
  return element.tagName === 'DIV';
})
console.log(`count = ${i}, result = ${result}`);
// count = 732, result = true
Rhys van der Waerden
  • 3,196
  • 2
  • 25
  • 31
5
if ( $('input.tb[value=""]').length > 0 ) // there are empty elements
adeneo
  • 303,455
  • 27
  • 380
  • 377
5

I am adding this a year late for others who stumble across this:

Malk's answer will fulfill the EXACT requirements in your example with:

$('input.tb').filter(function() { return this.value.length == 0}).length != 0;

A slightly more performant way of doing this (if the condition is met early, the filter function will still iterate over the remaining DOM elements) would be to write your own helper method (which, admittedly, the op has stated

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

, but I came to this page hoping to save 2 mins writing my own):

;(function($) {
    //iterates over all DOM elements within jQuery object
    //and returns true if any value returned from the supplied function is 'truthy'.
    //if no truthy values are returned, returns false.
    //
    //Function( Integer index, Element element ) 
    $.fn.any = function(fn) {
       var i=0;
       for (;i<this.length;i++) {
          if (fn.call(this[i],i,this[i])) {return true;}
       }
       return false;
    }
)(jQuery);
Brent
  • 4,249
  • 4
  • 33
  • 48
1

There's no jQuery need for this, as javascript arrays have the .some function (as long as you're not using IE < 9). Then you could do something like:

// toArray() called for being a jQuery element, we need an array for this
$('input.tb').toArray().some((elem) => elem.length == 0);

And FWIW, there's also the .every function, which returns true when all the elements pass the function.

Alter Lagos
  • 11,009
  • 1
  • 70
  • 87