Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking form input values with jquery

Tags:

html

jquery

forms

I have a form that I want jquery to check and see if the input/select values with a class of required (These classes are in the #customerForm form) are blank. If they are I would like to prevent the form from submitting and change the color of the input/select box to red. If all of the input/select values with a class of required do have values, I would like to submit the form, fade the form inputs out and and fadeIn the next form. Here's my code:

$('#customerForm').submit(function (event) {
    var value = $('.required').each();
    if (value === "") {
        value.addClass("invalid");
        return false;
    } else {
        value.removeClass("invalid");
        $('#billForm, #shipForm').fadeOut();
        $('#payment-form').fadeIn();
    }
}); 

The problem is the form doesn't check for the input values and submits the form anyways. Any help would be amazing.

like image 990
Carl Jones Avatar asked Jun 29 '26 12:06

Carl Jones


1 Answers

$('.required').each() returns an array of inputs.

You have to loop through each input and check the value before the form can be submit.

$( ".required" ).each(function() {
  //validation
});

more complete example:

$('#customerForm').submit(function (event) {
  var error = false;
  $( ".required" ).each(function() {
    if ($(this).val() === "") 
    {
      $(this).addClass("invalid");
      error = true;
    } 
    else 
    {
      $(this).removeClass("invalid");
    }
  });
  if(!error)
  {
    $('#billForm, #shipForm').fadeOut();
    $('#payment-form').fadeIn();
  }
  else
  {
    return false;
  }
}); 
like image 135
Bart Avatar answered Jul 01 '26 02:07

Bart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!