I have this code:
kreiraj_korisnika.on('submit', function(){
if(error_count != false) {
kreiraj_korisnika.submit();
} else {
return false;
}
});
How can I continue with form submitting when error_count is true (without AJAX submit)?
You have to use preventDefault() method of event variable to avoid the submit. Try sopmething like:
kreiraj_korisnika.on('submit', function(e) {
if (error_count)
{
// avoid the submit...
e.preventDefault();
// show your erros messages
}
});
If error_countvariable is true, the submit will happen.
Is kreiraj_korisnika actually an jQuery object ?
If you just assigned it to a result of getElementById() it won't work.
In that case:
$(kreiraj_korisnika).on('submit', function(e){
var errorCount = 0;
if(errorCount == 0)
{
this.submit();
}
else
{
alert('Invalid form input !');
e.preventDefault();
}
});
Léon
Related
My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();
I have a form I am implementing some custom validation on. This is the block of JavaScript that handles the final check before the form is submitted:
$('.enquiry-form-container form').submit(function (e) {
e.preventDefault();
var invalid = false;
var isblank = false;
//Loop through each input and check if valid or empty
$('.validate').each(function () {
if ($(this).hasClass('invalid')) {
isInValid($(this));
invalid = true;
} else {
//Any fields are blank
if ($(this).val() === "") {
$(this).addClass('blank');
isblank = true;
} else {
$(this).addClass('valid');
isValid($(this));
$(this).removeClass('blank empty');
}
}
});
if (!invalid & !isblank){ //SEND
$(this).find(":submit").prop("disabled", true); //Prevent submit to prevent duplicate submissions
$(this).submit();
} else { //DONT SEND
}
});
Each time I fill out the form and attempt to submit I get the following error in the console:
Uncaught RangeError: Maximum call stack size exceeded(…)
I understand that this can happen for a number of reasons, usually an infinite loop. Can anyone see where I am going wrong in the above code? Is the .submit() function calling the submit() method again... If so how can I resolve this and send form if it validates?
Just for full clarity, here is my isInValid() and isValid() functions.. They are used to add or remove the appropriate classes so I can style the inputs differently depending on the input.
//VALID INPUT
function isValid(input) {
input.addClass('valid');
input.removeClass('invalid empty blank');
input.parent().parent().next('.hint').css('visibility', 'hidden');
}
//INVALID INPUT
function isInValid(input) {
input.addClass('invalid');
input.removeClass('valid empty blank');
input.parent().parent().next('.hint').css('visibility', 'visible');
}
Generally, you just need to worry about cancelling an event in the if/then branches of your validation logic that indicate a problem. If you don't hit those branches, the form submits as it normally would. This removes the need for you to manually indicate that you want the form submitted.
See comments inline below for details:
$('.enquiry-form-container form').submit(function (e) {
var invalid = false;
var isblank = false;
// Loop through each input and check if valid or empty
$('.validate').each(function () {
if ($(this).hasClass('invalid')) {
isInValid($(this));
invalid = true;
e.preventDefault();
return;
} else {
// Any fields are blank
if ($(this).val() === "") {
$(this).addClass('blank');
isblank = true;
e.preventDefault();
return;
} else {
$(this).addClass('valid');
isValid($(this));
$(this).removeClass('blank empty');
}
}
});
// If we've gotten this far, the form is good and will be submitted.
// No need for an if/then/else here because you've already trapped
// the conditions that would prevent the form from being submitted
// above.
// Prevent submit to prevent duplicate submissions
$(this).find(":submit").prop("disabled", true);
});
It's also a good idea to separate your validation code into its own function, so a reworked example would be:
$('.enquiry-form-container form').submit(function (e) {
// You only need to worry about cancelling the form's submission
// if the form is invalid:
if (!validate()) {
e.preventDefault();
return;
}
// If it is valid, you don't need to interfere in that process, but
// you can certainly do other "valid" operations:
// Prevent submit from being clicked to prevent duplicate submissions
$(this).find(":submit").prop("disabled", true);
});
function validate() {
// This function doesn't worry about cancelling the form's submission.
// Its only job is to check the elements, style them according to
// their validity (and, in a perfect world, the styling would be off-
// loaded to anther function as well) and return whether the form is
// valid or not.
var invalid = false;
var isblank = false;
// Loop through each input and check if valid or empty
$('.validate').each(function () {
if ($(this).hasClass('invalid')) {
isInValid($(this));
invalid = true;
} else {
// Any fields are blank
if ($(this).val() === "") {
$(this).addClass('blank');
isblank = true;
} else {
$(this).addClass('valid');
isValid($(this));
$(this).removeClass('blank empty');
}
}
});
// If invalid or isblank is true, there was a problem and false
// should be returned from the function
return !invalid || !isblank;
}
I think the main problem for you is calling submit() from inside the handle of the submit. the better way to do this is cancel the request just when you see that there is invalid data.
$('.enquiry-form-container form').submit(function (e) {
e.preventDefault();
var invalid = false;
var isblank = false;
//Loop through each input and check if valid or empty
$('.validate').each(function () {
if ($(this).hasClass('invalid')) {
isInValid($(this));
invalid = true;
} else {
//Any fields are blank
if ($(this).val() === "") {
$(this).addClass('blank');
isblank = true;
} else {
$(this).addClass('valid');
isValid($(this));
$(this).removeClass('blank empty');
}
}
});
if (!invalid & !isblank){ //SEND
$(this).find(":submit").prop("disabled", true); //Prevent submit to prevent duplicate submissions
return true;
} else { //DONT SEND
return false;
}
});
I think the main problem for you is calling submit() from inside the handle of the submit. the better way to do this cancels the request just when you see that there is invalid data.
$('.enquiry-form-container form').submit(function (e) {
// remove the e.preventDefault();
var invalid = false;
var isblank = false;
//Loop through each input and check if valid or empty
$('.validate').each(function () {
if ($(this).hasClass('invalid')) {
isInValid($(this));
invalid = true;
} else {
//Any fields are blank
if ($(this).val() === "") {
$(this).addClass('blank');
isblank = true;
} else {
$(this).addClass('valid');
isValid($(this));
$(this).removeClass('blank empty');
}
}
});
if (!invalid & !isblank){ //SEND
$(this).find(":submit").prop("disabled", true); //Prevent submit to prevent duplicate submissions
//$(this).submit(); // this should be removed
} else { //DONT SEND
e.preventDefault();
}
});
I have these JQuery functions:
function CheckRequired() {
$(".required").each(function(event) {
var check = $(this).val();
if(check == '') {
event.preventDefault();
alert("One or more fields cannot be blank");
//alert($(this).attr("id"));
return false;
}
return true;
});
}
$(document).ready(function() {
$("form").each(function() {
$(this).submit(function(event) {
CheckRequired();
});
});
});
so my required fields have a class of required but when submitting a form, its showing the alert error but it still submits the form
how can i stop it submitting the form if there is an error
The result of CheckRequired() is not being returned from the submit handler.
return CheckRequired();
You might also pass the event into that function and in the case that you do not want the submit to happen, inside CheckRequired do
event.preventDefault();
I'll redo the code block...
function CheckRequired(event) {
var $form = $(this);
if ($form.find('.required').filter(function(){ return this.value === '' }).length > 0) {
event.preventDefault();
alert("One or more fields cannot be blank");
return false;
}
}
$(document).ready(function () {
$('form').on('submit', CheckRequired);
});
Try this:
$(document).ready(function() {
$("form").submit(function(event) {
if ( !CheckRequired() ){
event.preventDefault();
}
});
});
And I am smelling bug in the code. You are looping through each form, and for checking required you are doing a global find for .required
and here's the little refactor you can do to the CheckRequired function:
function CheckRequired() {
var field_with_empty_ip = $(".required").filter(function(){
return ( $(this).val() == "" );
});
return ( field_with_empty_ip.length < 0 );
}
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 */ }
I try to prevent a form submitting, with the following script, but it always does. I have even tried preventDefault() on document load, but it does not work.
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
$("form").submit(function(e) {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
}
else{
$("span").text("Passwords do not match!").show().fadeOut(1000);
e.preventDefault();
}
});
You need to use preventDefault() to cancel the action. Note the parameter e that I added to the anonymous function call.
My suggestion, or the way I normally go about this is like this:
$("form").submit(function(e) {
e.preventDefault(); // form never fires unless I want it to
if( condition == true ) {
$(this).submit();
} else {
//Don't submit
}
}
Here is a great explanation of why preventDefault() > return false
In order for this to close I think I have found something, but it's absurd at best. My functions work when they are in a $(document).ready. Why? I would be glad to listen to your advice.
$(document).ready(function(){
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
});