The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late). But yes, put return false at the end of your function.
Try this:
$("#cpa-form").submit(function(e){
return false;
});
Use the new "on" event syntax.
$(document).ready(function() {
$('form').on('submit', function(e){
// validation code here
if(!valid) {
e.preventDefault();
}
});
});
Cite: https://api.jquery.com/on/
This is an ancient question, but the accepted answer here doesn't really get to the root of the problem.
You can solve this two ways. First with jQuery:
$(document).ready( function() { // Wait until document is fully parsed
$("#cpa-form").on('submit', function(e){
e.preventDefault();
});
})
Or without jQuery:
// Gets a reference to the form element
var form = document.getElementById('cpa-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {
e.preventDefault();
});
You don't need to use return false
to solve this problem.
I believe that the above answers is all correct, but that doesn't point out why the submit
method doesn't work.
Well, the submit
method will not work if jQuery can't get the form
element, and jQuery doesn't give any error about that. If your script is placed in the head of the document, make sure the code runs after DOM
is ready. So, $(document).ready(function () { // your code here // });
will solve the problem.
The best practice is, always put your script in the bottom of the document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With