Chrome crashes with this JS - javascript

Chrome crashes with this JS.
There is a form with multiply inputs. The JS code has to check before submit were they filled or not. But after success submit Chrome crashes.
<script>
$(document).ready(function(){
var form = $('form#add');
form.submit(function(){
var filledInputs = $('form#add input[value!=""]');
$('form#add input[value=""]').css('border','solid 1px red');
filledInputs.css('border','');
if (filledInputs.length >= 9) {
form.submit();
return true;
} else {
return false;
}
});
});
</script>

You're function is infinitely recursive when there are >=9 filled inputs. On submit, the form performs validation, if the validation passes, you make another call to submit, which validates the form, and so on.
If you remove the form.submit(); and just return true the form will submit correctly.

Your form is already submitted, you don't need to submit it again :
if (filledInputs.length >= 9) {
// form.submit();
return true; // return true is to continue with the form submission
} else {
return false;
}

Shortening the code a bit makes the problem obvious:
form.submit(function(){
form.submit();
})
This is causing an infinite recursion, which exhausts the stack, and causes usually causes chrome to abort the script (or to crash).

You can just do this:
form.submit(function () {
var filledInputs = $('form#add input[value!=""]');
$('form#add input[value=""]').css('border', 'solid 1px red');
filledInputs.css('border', '');
return (filledInputs.length >= 9);
});
form will be submitted based on the input fields validation.

Related

Form submit after preventDefault

I'm trying to validate a form before it is submitted. I've tried a couple of methods but I cant get the form to submit after preventDefault. This is the code I have at the moment:
$('#formquote').submit(function(e){
e.preventDefault();
console.log('here');
validating = true;
var tval = valText('input[name=contactname]');
var pval = valPhone('input[name=telephone]');
var eval = valEmail('input[name=email]');
console.log(tval);
console.log(pval);
console.log(eval);
if(tval && pval && eval){
$("#formquote").unbind('submit');
$("#formquote").submit();
}
});
The console logs you can see output as expected ('here', true, true, true respectively)
At the moment the form submits on the second time you press the button. I've also tried the following suggestions to no avail:
-> $("#formquote").unbind('submit').submit(); //same result
-> $("#formquote").submit(); //by itself, infinite loop
-> $("#formquote")[0].submit(); //non function error
-> $('#formquote').unbind('submit', preventDefault); //'preventDefault' not defined
Any help would be appreciated
Instead of always preventing the form from submitting, doing your validation and submitting again if it passes, why don't you just prevent the submission when the validation fails? Something like this:
$('#formquote').submit(function (e) {
validating = true;
var tval = valText('input[name=contactname]');
var pval = valPhone('input[name=telephone]');
var eval = valEmail('input[name=email]');
if (!(tval && pval && eval)) {
e.preventDefault();
}
});
I guess the accepted answer is the best way of doing this, but if, for some reason, you need to use preventDefault() first and then submit the form, this works for me:
$('#formquote').on('submit', function (e) {
e.preventDefault();
// Do validation stuff..
// Then submit the form
$(this).submit();
}

jQuery Validate stop form submit

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

How to capture an html form submit with javascript?

Currently I have several text inputs and then a type image submit button. On the submit button I have onmouseover, onmouseout, etc.. This sends those to a javascript function that handles change of images for a hover effect. What I wanna do is submit the form and then do some checking like do passwords match and such. Would I do something with the action attribute of the form tag to submit it to a javascript function?
Firstly I recommend using something like jQuery. It makes the code a lot easier to manage. Here's how you'd do it in jQuery:
$('form').submit(function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
Here's how you'd do it in pure javascript:
// function to make sure we add the event correctly no matter which browser
function addEvent(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
}
// get first form on page
var form = document.forms[0];
addEvent('submit', form, function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
<form onsubmit="return cancel()"><input type="submit" /></form>
<script>
function cancel()
{
//code validation
var validated = false;
if(!validated)return false;
else return true;
}
</script>

Re-enabling Submit after prevent default

I am trying to unbind or reenable the prevent default so my form will submit on good data.
I have tried multiple examples. Here is my code and some of the examples i tried.
This code works great for what i want to. Just the last thing and resetting the div which i can implement after i get this.
function lengthRestriction(elem, min, max) {
var uInput = elem.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
var cnt = document.getElementById('field');
cnt.innerHTML = "Please enter between " + min + " and " + max + " characters";
elem.focus();
$('#ShoutTweet').submit(function(e) {
e.preventDefault();
//bind('#ShoutTweet').submit();
//$('#ShoutTweet').trigger('submit');
});
}
}​
i have a jsbin set up too http://jsbin.com/ebedab/93
Don't try to set up and cancel a submit handler from within your validation function, do it the other way around: call the validation from within a single submit handler, and only call .preventDefault() if the validation fails:
$(document).ready(function() {
$('#ShoutTweet').submit(function(e) {
if (/* do validations here, and if any of them fail... */) {
e.preventDefault();
}
});
});
If all of your validations pass just don't call e.preventDefault() and the submit event will then happen by default.
Alternatively you can return false from your submit handler to prevent the default:
$('#ShoutTweet').submit(function(e) {
if (!someValidation())
return false;
if (!secondValidation())
return false;
if (someTestVariable != "somevalue")
return false;
// etc.
});
I'm not completely sure what you are asking, but if your goal is to destroy your custom submit handler, then use this:
$("#ShoutTweet").unbind("submit");
This assumes that you have a normal (not Ajax) form.
Just call submit on the form
$('#ShoutTweet').submit();
This works surely and enable form submission after event.preventDefault();
$('#your-login-form-id').on('submit', onSubmitLoader);
function onSubmitLoader(e) {
e.preventDefault();
var self = $(this);
setTimeout(function () {
self.unbind('submit').submit(); // like if wants to enable form after 1s
}, 1000)
}

jQuery: Stop submitting form, perform script, continue submitting form?

I have a form, and when I submit him I execute multiple script. Here is my code:
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
//How to continue submitting?
}
Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?
Thank you
When you call $("#RequestCreateForm").submit(), the script will just run through the event handler again, and cause an infinite loop (as Koen pointed out in a comment on the accepted answer). So, you need to remove the event handler before submitting:
$("#RequestCreateForm").on('submit', function (e) {
e.preventDefault();
// do some stuff, and if it's okay:
$(this).off('submit').submit();
});
The last line needs to be in a conditional statement, otherwise it'll just always happen, and negate your e.preventDefault(); at the top.
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() === false) {
e.preventDefault();
//form was NOT ok - optionally add some error script in here
return false; //for old browsers
} else{
//form was OK - you can add some pre-send script in here
}
//$(this).submit();
//you don't have to submit manually if you didn't prevent the default event before
}
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false)
{
e.preventDefault();
return false;
}
//other scripts
}
All solutions here are too complicated or lead to javascript error, simpliest and clearest solution I guess:
jQuery("#formid").submit(function(e) {
if( ! (/*check form*/) ){ //notice the "!"
e.preventDefault();
//a bit of your code
} //else do nothing, form will submit
});
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
// Bypass the jquery form object submit and use the more basic vanilla
// javascript form object submit
$("#RequestCreateForm")[0].submit();
}
To avoid submit loops, an additional variable should be used.
var codeExecuted = false;
$('#RequestCreateForm').submit(function(e) {
...
if(!codeExecuted){
e.preventDefault();
...
functionExecuted = true;
$(this).trigger('submit');
}
});
Here is my approach to avoid the infinite loop.
In the form, I use a "button" with an id (e.g. <input type="button" id="submit" value="submit"/>) to mimic the submit button;
In the script I have something like this:
$('#submit').click(function() {
if(//validation rules is ok)
{
$("#RequestCreateForm").submit(); //assuming the form id is #RequestCreateForm
}
else
{
return false;
}
});
return; is the same thing as e.preventDefault();
try
$("#RequestCreateForm").trigger('submit');

Categories