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,570
  • 20
  • 66
  • 101

6 Answers6

19

The problem with jQuery's built-in filtering functions like .is(), .has(), and .filter() is that none of them short circuit as soon as the criteria is met.

This is good use case where we can reach for a native ES6 method like Array.some() by converting to an array first:

$(":input").toArray().some((el) => $(el).val().length === 0)

If you really wanted, you could write an extension method like this:
(though it's probably not necessary)

jQuery.fn.some = function(filter) {
    return this.toArray().some(filter)
}

// then use it like this:
var someEmpty = $(":input").some(function(el) { 
    return $(el).val().length === 0
});

Working demo in Stack Snippets

jQuery.fn.some = function(filter) {
    return this.toArray().some(filter)
}

function checkEmpty() {
    var someEmpty = $(":input").some(function(el) { 
      return $(el).val().length === 0
    });

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

$(function() {
  $(":input").change(checkEmpty)
  checkEmpty() // fire once on init
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>

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

Related Posts

KyleMit
  • 30,350
  • 66
  • 462
  • 664
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,855
  • 4
  • 33
  • 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,526
  • 2
  • 27
  • 32
5
if ( $('input.tb[value=""]').length > 0 ) // there are empty elements
adeneo
  • 312,895
  • 29
  • 395
  • 388
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,611
  • 4
  • 38
  • 55
2

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
  • 12,090
  • 1
  • 70
  • 92