jQuery Validate stop form submit - javascript

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;
});

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
}
}
});

Related

Stop a form from submitting

I have a form which is submitted using Ajax.
If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.
If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.
The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.
I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.
function check() is attached to the submit button.
Any and all advice is welcome.
If I can provide any additional information, let me know.
Thank you
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
As chandan suggested, I edited function check() and it works.
RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.
Anyway, this is the code that does the job:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
Function check() should work without any edits then.
Also, see code from this question

MVC - Issue with users double-clicking Submit button

I have a number of pages in my MVC app where the user clicks a Submit button to post a form. Sometimes users will click Submit and since nothing happens immediately, click it again. Therefore, the form submits twice. To prevent this, I have the following JavaScript code:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
This code disables the Submit button so the user cannot click twice. This works fine. However, if there are client side validation errors on the form, the Submit button gets disabled but the form is never posted, and now the user cannot post the form. Is there a change I can make to the JS code to detect if there were client side validation errors, and, if so, I either don't disable the Submit button, or reenable it?
If you are using jQuery Validate, you can check to see if the form is valid before disabling the button:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
You can try something like this:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
Switch it around.
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});

Check existing mail with ajax and PHP

Is there any method to check if the mail (in a registration form) exist in my database while i'm writing it (before i click submit buttom).
This is my javascript function it work well when I click submit button:
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#_submit').click(function() {alert('in');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {'mail' : emailVal}, function(data) {
if(data=='exist') return false;
else $('#form1').submit();
});
});
});
</script>
but I want to verify the mail before I submit (without I click any button)
I believe #_submit is a submit button. In that case, your <from> will be submitted without waiting for the ajax call to complete, since that is an asynchronous task.
In order to work around this, you should prevent the <form> submission by default, and once the ajax call completes, decide whether to submit the form or not depending on the response.
$(document).ready(function() { //newly added
$('#_submit').click(function(e) {
e.preventDefault(); // prevent default submission
alert('in, submission prevented - waiting for ajax response');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {
'mail': emailVal
}, function(data) {
if (data == 'exist')
return false;
else
$('#form1').submit();
});
});
});
or you can simply use a type="button" button so that it doesn't trigger <form> submission.
something like that
$.ajax(url).done(function(response) {
if (response === true) {
$(form).submit();
} else {
console.log("not allowed");
});

How to prevent submit but still validate required fields?

I have a form, and when is submitted I prevent it with e.preventDefault(), but I still want the browser to validate the required fields before I make the AJAX call.
I don't want to get fancy with javascript validation, I just want the browser to validate the required fields (HTML5).
How can I achieve this?
It works, even if you don't do the checkValidity check. In chrome, it won't call the submit function on the form if form is not valid:
$(document).ready(function(){
$("#calendar_form").submit(function(e){
e.preventDefault();
calendarDoAjax();
});
function calendarDoAjax(){
var proceed = false;
if( $("#calendar_form")[0].checkValidity ){
if ($("#calendar_form")[0].checkValidity()) {
proceed = true;
}
}else{
proceed = true;
}
if (proceed) {
//Do ajax call
}
}
});
Add this in the end of your submit function:
if (evt && evt.preventDefault) {
evt.preventDefault();
} else if (event) {
event.returnValue = false;
}
return false;
And pass the var evt in your function like this:
function(evt) { /* Your Code */ }

How do I trigger Form Submission in Javascript?

I have initialized my form submission like following:
$(document).ready(function() {
$("#my_form").submit(function(e) {
...
...
}
}
As you see above, it is in $(document).ready(...). When user press "Submit" button on UI, the form will be submitted.
But, How can I also trigger this form submission in Javascript besides user input (e.g. press submit button on UI)?
Call the submit() DOCs method on the form.
$("#my_form").submit();
You can use $("#my_form").submit();
$(document).ready(function () {
$("#SubmitForm").click(function (e) {
var textContent = $("#TextContent").val();
textContent = jQuery.trim(textContent);
if (textContent == "") {
alert("Content field cannot be empty.");
$("#TextContent").focus();
return false;
}
else{ $("#my_form").submit();
}
});
});

Categories