6

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.

0

3 Answers 3

11

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I had to make a contribution one way or another :). No problemo.
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!
4

Try this jQuery selector:

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

JS Documentation: Selectors

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.