Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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

like image 852
Javi Avatar asked Nov 29 '22 05:11

Javi


2 Answers

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 is type='text'. (See the docs.)
  • Because these are text inputs, it is quicker to use this.value than $(this).val().
  • No need to get the 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')
like image 38
user113716 Avatar answered Dec 05 '22 12:12

user113716


$(':text').filter(function () {
    return $.trim($(this).val()).length === 0;
});
like image 79
Domenic Avatar answered Dec 05 '22 13:12

Domenic