jquery return false killed submit event? - javascript

I try to use loop to validate each of every input whether they are filled or not. But end up my submit_form function doesn't get triggered.
$('#submit').click(function(){
var hold = true;
if ($('.tab2').hasClass('active') && hold == true) {
$('.tab-content:visible input').each(function(i, val) {
if ($(this).val() == '') {
alert("Please fill in valid " + $(this).attr('data-error'));
$(this).focus();
hold = true;
return false;
} else {
hold = false;
}
});
return false; //can't remove this
}
submit_form(); //not triggered although all inputs are filled
})
if I removed the return false, there will be no checking..

Related

JQuery RangeError On form submit

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

Disable an input after click and validation occurs

I'm trying to disable an input in a form, but only after validation of fields.
function valJomclAddForm() {
f = document.jomclForm;
document.formvalidator.setHandler('list', function (value) {
return (value != -1);
});
if (document.formvalidator.isValid(f)) {
if(document.getElementById('membership6') === null) {
return false;
}
jQuery('input#submit').val('Publishing...');
jQuery('input#submit').prop('disabled', true);
return true;
} else {
//alert
}
}
but when function gets here:
jQuery('input#submit').prop('disabled', true);
return true;
Function stops, change input value to "Publishing" but doesn't publish, doesn't get the "return true"
Unless I remove jQuery('input#submit').prop('disabled', true);then function return true and publish this...
Why does this not work?
Thanks a lot in advance!

Wait for the return of the loop on form submit

I have the code below, the form is needed to be validated before it can submit the form.
But the problem is, the form continues to submit without validating.
<form action='#' method='post' onsubmit='return validate();'>
function validate()
{
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
}
});
});
How to handle the return of a loop?
Dont submit the form once encountered return false on the loop.
try this:
function validate()
{
var passes = true;
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
passes = false;
}
}
});
return passes;
});
Do not use return.
$('#my-form').on('submit', function(event){
if (validate() === false) {
event.preventDefault(); // like return false;
}
});
For more information see jQuery submit docs.
Each function has it's own returned value, the default returned value is an undefined value. You should check the length of the invalid elements after the each loop and return a proper value, since you are using jQuery I'd suggest:
$('form').on('submit', function (event)
{
var $invalid = $(this)
.find(':input:not(:submit,:hidden), select, textarea')
.removeClass('redBox')
.addClass(function () {
return this.getAttribute('requiredz')
&& $.trim(this.value) === ''
? 'redBox'
: null;
}).filter('.redBox');
if ($invalid.length)
{
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
});

Form refresh after .submit() event

I am validating a form that's working fine but i don't know why the form not submit after all validations.
Here is validation code:
$('#coupon_options').submit(function(e){
e.preventDefault();
var name = $('input[name="coupon_name"]'),
code = $('input[name="coupon_code"]'),
value = $('input[name="coupon_value"]'),
valid = $('input[name="coupon_valid"]'),
status = true;
if( $.trim(name.val()) == "" ){
name.css('border-color', '#ff0000');
status = false;
} else { name.removeAttr('style'); }
if( $.trim(code.val()) == "" ){
code.css('border-color', '#ff0000');
status = false;
} else { code.removeAttr('style'); }
if( $.trim(value.val()) == "" ){
value.css('border-color', '#ff0000');
status = false;
} else { value.removeAttr('style'); }
if( $.trim(valid.val()) == "" ){
valid.css('border-color', '#ff0000');
status = false;
} else { valid.removeAttr('style'); }
if( status == true ){ return status; }
else { return false; }
});
As i know to stop the refresh after submit event i have used the return false but i am not sure return true works here or not?
I don't want to use Ajax, just want to submit after validation.
Is there something wrong in this code??
remove:
e.preventDefault();
it stopping the default action to occur even you return true;.
For example:
Prevent a submit button from submitting a form
Prevent a link from following the URL
e.preventDefault(); is the issue, but you should note that it's never a good sign when you have multiple functions that basically perform the same action for different elements, you can simplify your code to this:
$('#coupon_options').submit(function(e){
var status = true;
$('input[name="coupon_name"],input[name="coupon_code"],input[name="coupon_value"],input[name="coupon_valid"]').each(function(){
if($.trim($(this).val()) == ""){
$(this).css('border-color', '#ff0000');
status = false;
} else {
$(this).removeAttr('style');
}
});
return status;
});
And you could even use $('input[name^="coupon_"]') to select all inputs that start with that prefix.

Different forms with the same Submit function

I have many forms generated dynamically via PHP. I'm trying to verify that all the fields on the one form that's going to be submitted are filled. I'm just starting to JQuery, so I'm sorry if the answer is stupidly easy.
I tried this:
$('.myform').submit(function(){
var flag = true;
$('.myform input').each(function() {
if($(this).val() === ''){
flag = false;
return false;
}
});
return flag;
});
But when in the second form, it goes and checks the first one (which should be empty because you're not filling that one...)
Thanks in advance!
$('.myform').submit(function(){
var flag = true;
// use $(this) below which is the form has submit event fired.
$(this).find('input').each(function() {
if($(this).val() === ''){
flag = false;
return false;
}
});
return flag;
});
Or you could simplify your code by:
$('.myform').submit(function() {
return $(this).find('input').filter(function() {
return $.trim($(this).val()) !== '';
}).length == 0;
});

Categories