最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to make trim in a selector? - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Nov 24, 2010 at 19:33 casperOne 74.5k19 gold badges189 silver badges260 bronze badges asked Nov 24, 2010 at 19:29 JaviJavi 19.8k32 gold badges107 silver badges138 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12
$(':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/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/patrick_dw/mjuyk/1/

$('input:text').not(function () {
    return $.trim(this.value);
});

Also, you can create a custom selector like this:

Example: http://jsfiddle/patrick_dw/mjuyk/2/

$.extend($.expr[':'], {
   novalue: function(elem, i, attr){
      return !$.trim(elem.value);
   }
});

$('input:text:novalue')
发布评论

评论列表(0)

  1. 暂无评论