Is It Possible To Make Trim In A Selector?
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).
Solution 1:
$(':text').filter(function () {
return $.trim($(this).val()).length === 0;
});
Solution 2:
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);
});
- You should specify
input:text. Otherwise jQuery needs to observe every element in the DOM to see if it istype='text'. (See the docs.) - Because these are text inputs, it is quicker to use
this.valuethan$(this).val(). - No need to get the
lengthproperty 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')
![Uncaught Typeerror: Object [object Object] Has No Method 'apply'](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEZR1HtNb7Cu-zFkWj8JhcNIalqp5JuTCYC04mfY9PnrEAiY6hwfgJmH0aOmBhUm4JJDR_oj_8TY8PTKMiPPS1YbcZJBqYYqP0fxcExVfJ4ROdgVGPrvVGNQIQRCXgdy2asyrxtLmRb40/w192-h108-n-k-rw-no-nu/nomage+%25281%2529.png)
Post a Comment for "Is It Possible To Make Trim In A Selector?"