JQuery - Find any input with a given class that doesn't matter

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

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

Adding this function to my onSubmit handler of my form does not return any results. Any light shed on this issue will be appreciated.

I am basically following a function that iterates through all the inputs with the .required class, and if ANY has an empty or 0 value, return false in my submit and change the background color of all incorrectly executed inputs to orange.

+5
3

.val() .required, .val():

.

, :

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

:

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

jQuery:

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

+3

, jQuery:

$(document).ready(function(){

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

:

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

, .each:

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

All Articles