Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 236
SimonDowdles Avatar asked Aug 13 '10 13:08

SimonDowdles


1 Answers

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;
}
like image 60
Nick Craver Avatar answered Sep 28 '22 15:09

Nick Craver