开发者

jQuery - Find any input with a given class that has no value

I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:

function myValidation(){
  if($(".required").val() == "" || $(".required").val() == 0){
  $(this).css({ backgroundColor:'orange' })  ;
  return false;
  }
}

Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be app开发者_运维百科reciated.

I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.


Your code currently gets the .val() for the first .required, from the .val() documentation:

Get the current value of the first element in the set of matched elements.

You need to filter through each one individually instead, like this:

function myValidation(){
  var allGood = true;
  $(".required").each(function() {
     var val = $(this).val();
     if(val == "" || val == 0) {
       $(this).css({ backgroundColor:'orange' });
       allGood = false;
     }
  });
  return allGood;
}

Or a bit more compact version:

function myValidation(){
  return $(".required").filter(function() {
     var val = $(this).val();
     return val == "" || val == 0;
  }).css({ backgroundColor:'orange' }).length === 0;
}


Try this jQuery selector:

$('.required[value=""], .required[value=0]')


You could also do it by defining your own custom jQuery selector:

$(document).ready(function(){

    $.extend($.expr[':'],{
        textboxEmpty: function(el){
            return ($(el).val() === "");
        }
    });
});

And then access them like this:

alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection

So you could put a .each on them:

$('input.required:textboxEmpty').each(function(){
    //do stuff
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜