I am using jQuery validate to the form, but when the form is validated it reloads or submits the page I want to stop that action. I already use the event.preventDefault(), but it doesn't work.
Here is my code:
$("#step1form").validate();
$("#step1form").on("submit", function(e){
var isValid = $("#step1form").valid();
if(isValid){
e.preventDefault();
// Things i would like to do after validation
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
$(".third_step_form").fadeIn();
$(".third_inactive").fadeOut();
}else if(counter < 3){
$(".second_step_form").fadeIn();
$(".third_inactive").fadeIn();
}
$(".first_step_summary").fadeIn();
$(".second_inactive").fadeOut();
}
return false;
});
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.
You need to do two things if validation fails, e. preventDefault() and to return false. This really works.
With the help of the event. preventDefault() method the event is to be stopped the form execution.
The submitHandler
is a callback function built into the plugin.
submitHandler
(default: native form submit):Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.
Since the submitHandler
automatically captures the click of the submit button and only fires on a valid form, you do not need another submit handler, nor do you need to use valid()
to test the form.
You code can be replaced with:
$("#step1form").validate({
submitHandler: function(form) {
// Things I would like to do after validation
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
$(".third_step_form").fadeIn();
$(".third_inactive").fadeOut();
}else if(counter < 3){
$(".second_step_form").fadeIn();
$(".third_inactive").fadeIn();
}
$(".first_step_summary").fadeIn();
$(".second_inactive").fadeOut();
return false; // block the default submit action
}
});
I use this basic structure for all my JS validation, which does what your asking
$('#form').on('submit', function() {
// check validation
if (some_value != "valid") {
return false;
}
});
You don't need e.preventDefault();
and a return false;
statement, they do the same thing.
The plugin provides callbacks for valid and invalid form submission attempts. If you provide a submitHandler callback then the form doesn't get submitted to the server automatically.
$("#step1form").validate({
submitHandler : function()
{
// the form is valid
$(".first_step_form").fadeOut();
if(counter == 3){
$(".second_step_summary").fadeIn();
// etc
}
}
});
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