“Any” boolean function in jquery

后端 未结 5 1198
再見小時候
再見小時候 2021-01-17 11:08

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

相关标签:
5条回答
  • 2021-01-17 11:30
    if ( $('input.tb[value=""]').length > 0 ) // there are empty elements
    
    0 讨论(0)
  • 2021-01-17 11:30

    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);
    
    0 讨论(0)
  • 2021-01-17 11:37

    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});
    
    0 讨论(0)
  • 2021-01-17 11:45

    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:


    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.


    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:

    • Jquery check form to see if any inputs has value
    • Is there an "exists" function for jQuery?
    • jQuery check if any text input has value
    0 讨论(0)
  • 2021-01-17 11:55

    .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
    
    0 讨论(0)
提交回复
热议问题