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?
I had the same problem and I solved this way (not elegant but it works):
And it has the advantage, in my opinion, that you can revert the situation any time you want:
$("#form')
looks for an element withid="form"
.$('form')
looks for the form elementYou forget the form id, and it works
I also had the same problem. I also had tried what you had tried. Then I change my method not to use jquery but by using "onsubmit" attribute in the form tag.
It works.
But, when I tried to put the false return value only in "thefunction()", it doesn't prevent the submitting process, so I must put "return false;" in onsubmit attribute. So, I conclude that my form application cannot get the return value from Javascript function. I don't have any idea about it.
Two things stand out:
form
. Rather refer to the tag by dropping the #.Also the
e.preventDefault
is the correct JQuery syntax, e.g.Option C should also work. I am not familiar with option B
A complete example:
Attach the event to the submit element not to the form element. For example in your html do like this