How do I prevent a form from submitting using jquery?
I tried everything - see 3 different options I tried below, but it all won't work:
$(document).ready(function() {
//option A
$("#form").submit(function(e){
e.preventDefault();
});
//option B
$("#form").submit(function(e){
stopEvent(e);
});
//option C
$("#form").submit(function(){
return false;
});
});
What could be wrong?
Update - here is my html:
<form id="form" class="form" action="page2.php" method="post">
<!-- tags in the form -->
<p class="class2">
<input type="submit" value="Okay!" />
</p>
</form>
Is there anything wrong here?
from here: https://api.jquery.com/submit-selector/ (interesting page on submit types)
You probably have few forms o the page and using $('form').submit() adds this event to the first occurrence of the form on your page. Use class selector instead, or try this:
or better version of it:
To prevant default/prevent form submission use
To stop event bubling use
To prevent form submission 'return false' should work too.
When I am using
<form>
tag without the attributeid="form"
and call it by its tag name directly in jquery it works with me.your code in html file :
and in Jquery script:
You may simply check if the form is valid if yes run submit logic otherwise show error.
HTML
Javascript