开发者

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 开发者_StackOverflow社区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


$(':text').filter(function () {
    return $.trim($(this).val()).length === 0;
});


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜