Form submit after preventDefault - javascript

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

Related

validator.js with bootstrap how do you know your form is valid on AJAX forms?

I'm using the validtor js tutorial to add it to my project.
I run this when button is clicked:
$("#add_now_btn").click(function(event){
//add now button
// event.preventDefault();
//$('#myOrderDetailsForm').validator();
var result = $('#myOrderDetailsForm').validator('validate');
The result is object, so how do I know if my form is valid prior to my AJAX call? In my current case 'validator' just runs and submits the form.
Docs
Try this
$('#form').validator().on('submit', function(e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
}
})
And you can use invalid.bs.validator to find errors in form (this works when a form field becomes invalid.)
$('form').validator().on('invalid.bs.validator', function (e) {
console.log(e)
})
And to get boolean value whether form is valid or not use this
$('form').validator().data('bs.validator').hasErrors();
returns true if form has errors and false if form is valid.
Why not to try this way? :
$('#myOrderDetailsForm').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
}
});

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

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

Chrome crashes with this JS

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.

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

Categories