Reputation: 2160
I want to prevent a form from being submitted once the submit button is clicked. It should capture all the data, but not send.
I've struggled with this a bit in an attempt to get it working, but to no avail. I've tried all the below methods, but nothing.
function saveDetails(form){
this.preventDefault();
}
function saveDetails(form){
$(form).preventDefault();
}
function saveDetails(form){
form.preventDefault();
}
I can capture the data easily by running $(form).serialize();
which works perfectly. But the above does not work for stopping the submit action. Any assistance?
Upvotes: 0
Views: 278
Reputation: 3765
In the function that is executed when the form is submitted, you need to pass in the event
object, which jQuery passes into all event callbacks, and then call preventDefault()
on that, eg:
function saveDetails(form, evt) {
evt.preventDefault();
var data = $(form).serialize();
// etc
}
$("form").on("submit", function(evt) {
saveDetails(this, evt);
});
Or simplify it a little:
function saveDetails(form) {
var data = $(form).serialize();
// etc
}
$("form").on("submit", function(evt) {
evt.preventDefault();
saveDetails(this);
});
Upvotes: 1
Reputation: 4470
you need to call it on event.preventDefault()
. preventDefault
is the method of the DOM event-object. For example, you need to attach a handler to the submit
event, that handler must do all what you need but inside itt you have to call this method
$('form').submit(function(e){
saveDetails();
e.preventDefault();
})
Upvotes: 2