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.
5 Different Ways to Declare Functions in jQuery.
The typeof operator when applied to the jQuery object returns the string "function" . Basically that does mean that jQuery is a function. But the typing sort of stops there.
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
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 (var 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 declarative code to use is
instead of filter
.
$.any()
in action:jQuery.fn.any = function(filter){
for (var 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="">
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With