I'd like to count all the inputs in my form which are empty. With empty I mean that its value is empty after trimming its value (if the user insert whitespaces its empty as well). This jquery count them, but it doesn't include the trimming:
$(':text').filter('[value=""]').length
Has something jquery which can be used to trim in the selector?
thanks
While the .filter()
method in @Domenic's answer is a good approach, I'd implement it a little differently.
Example: http://jsfiddle.net/patrick_dw/mjuyk/
$('input:text').filter(function () {
return !$.trim(this.value);
});
input:text
. Otherwise jQuery needs to observe every element in the DOM to see if it is type='text'
. (See the docs.)this.value
than $(this).val()
.length
property since an empty string is falsey. So just use the !
operator.Or you could use the inverse of .filter()
, which is the .not()
method:
Example: http://jsfiddle.net/patrick_dw/mjuyk/1/
$('input:text').not(function () {
return $.trim(this.value);
});
Also, you can create a custom selector like this:
Example: http://jsfiddle.net/patrick_dw/mjuyk/2/
$.extend($.expr[':'], {
novalue: function(elem, i, attr){
return !$.trim(elem.value);
}
});
$('input:text:novalue')
$(':text').filter(function () {
return $.trim($(this).val()).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