How to prevent submit but still validate required fields? - javascript

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 */ }

Related

Wizard Form not submitting

Wizard form is not submitting. Originally configured to give a notification when there are no errors instead of submitting. I want the form to submit. I therefore modified original code to as below
$w4finish.on('click', function(ev) {
ev.preventDefault();
var validated = $('#w4 form').valid();
if (validated) return true;
this.submit();
});
But it is still not submitting.
At this point fires return and further code is not executed.
if (validated) { return true }
Remove this line if not needed or change function to this one:
$w4finish.on('click', function(ev) {
ev.preventDefault();
var validated = $('#w4 form').valid();
if (validated) {
this.submit();
return true;
}
});

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>

Jquery - continue with form submit after validation

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

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