Zeeshan Ali
Zeeshan Ali

Reputation: 21

Prevent form from submission if error exists ajax .submit() with .change()

So I have this problem with jQuery/ajax code. I have used .change method whenever the field is changed. It shows the output whether that email is already taken or not or input field is empty. I know there is .submit method and preventDefault(), but I'm new to this and I get confused of how to use .change with .submit at a same time.

          pic1 = new Image(20, 20);
          pic1.src="images/abc.jpg";
          $(document).ready(function(){

          function isValidEmail(emailAddress) {
             // some regular expressions for email  format validation

      };
            $("#email").change(function() {
            var email = $("#email").val();
            if(isValidEmail(email)){

                $("#status").html('<img 
        style="width:17px;"src="images/abc.jpg" align="absmiddle">&nbsp;Checking availability...');

                $.ajax({ 

                type: "POST", 
                url: "check.php", 
                data: "email="+ email,
                dataType: 'text',

                    success: function(msg){

                        if(msg == 'OK'){
                         //alert ("success");
                $("#email").removeClass('object_error'); // if necessary
                $("#email").addClass("object_ok");
                $("#status").html('&nbsp;<img src="tick2.gif" 
               align="left"><p><strong style="color:green">This email is available</strong></p>');

            } else {
                //alert ("error");
               $("#email").removeClass('object_ok'); // if necessary
               $("#email").addClass("object_error");
               $("#status").html(msg);
           }
        }

    });

    } else {
      $("#status").html('<font color="red">' + 'Enter Valid 
     Email</font>');
     $("#email").removeClass('object_ok'); // if necessary
     $("#email").addClass("object_error");
   }
  });
 });

Upvotes: 2

Views: 267

Answers (1)

Kevin Wong
Kevin Wong

Reputation: 107

They are both events but for change and submit they behave differently.
They dont trigger at the same time.

For submit, it is an event to an element when the user is attempting to submit a form.
For change, it is an event trigger when the element values change.

Source :
1. https://api.jquery.com/submit/
2. https://api.jquery.com/change/

if you want to stop the default behaviour, you can check the added class (object_error) class during the change event.

$("form").on('submit', function (e) {
    if($('.object_error').length > 0){
         e.preventDefault();  
         return false;
    }
}

Upvotes: 1

Related Questions