JQuery logical iterators

... or what name is for some()and every(). Basically, I'm looking for a function or plugin that will allow me to write something like:

okay = $("#myForm input").every(function() { 
     return $(this).val().length > 0
})

or

hasErrors = $(listOfUsers).some(function() {
   return this.errorCount > 0;
})

You have an idea.

(Before the arriving team arrives, I googled and found jquery.arrayUtils , but this code does not look convincing me).

0
source share
2 answers

Simple, simple implementation:

$.fn.some = function(callback) {
    var result = false;
    this.each(function(index, element) {
        // if the callback returns `true` for one element
        // the result is true and we can stop
        if(callback.call(this, index, element)) {
            result = true;
            return false;
        }
    });
    return result;
};

$.fn.every = function(callback) {
    var result = true;
    this.each(function(index, element) {
        // if the callback returns `false` for one element
        // the result is false and we can stop
        if(!callback.call(this, index, element)) {
            result = false;
            return false;
        }
    });
    return result;
};

With ES5, arrays already provide methods everyand someso you can achieve the same with built-in methods:

okay = $("#myForm input").get().every(function(element) { 
     return $(element).val().length > 0
});

but it will not work in old version of IE without HTML5 shim .

+3
source

You can do something like this

okay = $("#myForm input").each(function() { 
     return $(this).val().length > 0
})

okay = $("#myForm input").find('class').each(function() { 
     return $(this).val().length > 0
})
0
source

All Articles