Is it possible to make trim in a selector?

老子叫甜甜 提交于 2019-12-10 16:48:40

问题


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


回答1:


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



回答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 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')


来源:https://stackoverflow.com/questions/4270727/is-it-possible-to-make-trim-in-a-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!