views:

37

answers:

3

Hi All,

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.

+3  A: 

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;
}
Nick Craver
+1 for reading the question properly, unlike me... again!
GenericTypeTea
@GenericTypeTea - thanks, and thanks for the type fix! :)
Nick Craver
@Nick - I had to make a contribution one way or another :). No problemo.
GenericTypeTea
@Nick - Spot On, works like a bomb thanks. May be worth mentioning that it did not work as a function on the onSubmit action of the form, but when used as a straight set of checks attached to $("#myForm").submit(function(){ ..code above goes here ... }); it worked like a dream, thanks!
webfac
A: 

Try this jQuery selector:

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

TimS
A: 

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
});
James Wiseman