简体   繁体   中英

Prevent form submission if there is errors

Basically i have a code that shows the user an error if the ID he wrote already exist or is too short but the problem is i can't figure out how to prevent the form from submission where there there is an error.

The code that needs to popup an alert window:

jQuery("#submit").click(function(e){

           if(error === '1')
           {
     alert("There are some errors in the form.");
     e.preventDefault();
           }
   });   

Then i get the answer using AJAX and showing up the error:

if(msg == 'OK')
{
var error = '0';
}
else
{
var error = '1';
jQuery("#idCheck_msg").slideDown("fast");
jQuery("#idCheck_text").text(msg).slideDown("fast");
}});
}

I have tried to do something with var error but Firebug says that error is not defined and the form get's submitted even when there is an error.

Any help? ;)

Define error as a global variable. That is remove var before using the variable:

var error;
if(msg == 'OK')
{
    error = '0';
}
else
{
    error = '1';
...

It appears that you're setting the value of error after the form is submitted but checking it's value before the form is submitted.

Given the code in your post, error will be undefined when you attempt to check it's value. In addition, after the form is submitted, error will still be undefined because you're declaring it within the scope of your AJAX response handler using the var keyword.

If you remove the var keyword from your AJAX handler when setting the value of error , your submission logic should work the second time around.

Bottom Line: The value of error needs to be set before your form is submitted, not in the AJAX response handler.

When is the AJAX call made? You won't be able to check 'error' until you get a success response from the AJAX call. Also you need to remove 'var' so it is in global scope.

If your AJAX call is also made when the form is submitted, you will need to move the error check to inside the code that handles the AJAX response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM