The problem with getting the length
property on filter()
is that jQuery will evaluate every single element in the collection, just to populate a count when all we care about is whether the value is greater than zero.
None of the current answers and even jQuery's own .is()
, .has()
, and .filter()
make use of short circuiting as soon as the criteria is met.
You can define a simple extension method called .any()
like this:
<!-- language: lang-js -->
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
And then pass in a filtering function like this:
<!-- language: lang-js -->
var someInputsEmpty = $("#reference,#pin,#fName,#mName,#datepicker").any(function() {
return this.value == '';
});
<!-- begin snippet: js hide: true console: true babel: false -->
<!-- language: lang-js -->
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
$(function() {
var gotMatch = $(":input").any(function() {
return this.value == 'hi';
});
if (gotMatch) {
console.log("Hello to you too!");
} else {
console.log("Why don't you say Hi!");
}
})
<!-- language: lang-html -->
<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="">
<!-- end snippet -->
Further Reading: