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:
$(docu
You forget the form id, and it works
$('form#form').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
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.
<form onsubmit="thefunction(); return false;">
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.
Using jQuery, you can do the following:
1- Use the native form submit event with a Submit button, while preventing the event from firing, then
2- Check the form Valid property This can be implemented as following:
1- HTML:
<form id="yourForm">
<input id="submit" type="submit" value="Save"/>
</form>
2- Javascript
$("form").on("submit", function (e) {
e.preventDefault();
if ($(this).valid()) {
alert('Success!');
}
});
This also appears to work and may be slightly simpler:
$('#Form').on('submit',function(){
return false;
})
Attach the event to the submit element not to the form element. For example in your html do like this
$('input[type=submit]').on('click', function(e) {
e.preventDefault();
});
// Prevent form submission
$( "form" ).submit(function( event ) {
event.preventDefault();
});
from here: https://api.jquery.com/submit-selector/ (interesting page on submit types)