Jquery Boolean Iterators
...or what's the proper name for some() and every(). Basically, I'm looking for a function or a plugin that would allow me to write something like: okay = $('#myForm input').every(
Solution 1:
A simple, straightforward 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 stopif(callback.call(this, index, element)) {
result = true;
returnfalse;
}
});
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 stopif(!callback.call(this, index, element)) {
result = false;
returnfalse;
}
});
return result;
};
With ES5, arrays already provide the methods every
and some
, so you could achieve the same with built in methods:
okay = $("#myForm input").get().every(function(element) {
return $(element).val().length > 0
});
but it won't work in older IE version without HTML5 shim.
Solution 2:
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
})
Post a Comment for "Jquery Boolean Iterators"