"Any" boolean function in jquery [duplicate]
Asked Answered
T

6

20

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.

Terrel answered 15/5, 2013 at 23:21 Comment(0)
F
20

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

Frustrate answered 7/4, 2017 at 15:42 Comment(0)
W
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});
Woozy answered 15/5, 2013 at 23:25 Comment(0)
R
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
Rataplan answered 10/10, 2014 at 0:36 Comment(0)
E
5
if ( $('input.tb[value=""]').length > 0 ) // there are empty elements
Estriol answered 15/5, 2013 at 23:25 Comment(0)
L
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);
Lydie answered 18/6, 2014 at 23:9 Comment(0)
D
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.

Doggish answered 26/2, 2021 at 4:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.