I'm trying to apply a simple form validation in jQuery. If a form field is empty, add a class error. If any of the fields are empty, don't submit. I have the following:
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$('#contact-form').submit();
}
});
});
Howerver when the code hits the line to submit the form, I am seeing a JavaScript error:
Uncaught RangeError: Maximum call stack size exceeded
Here's how your code would run if the form is valid:
on submit, prevent default action
check fields
if they are valid, form.submit - which causes submit event, goto step 1
endless recursion
it's very simple because there's no asynchronous code in the handler
$('#contact-form').submit(function(event) {
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
if (!formValid) {
event.preventDefault();
}
});
How many fields do you have to validate, and why promise associated to each of them? try after checking all fields
if(formValid) {
$('#contact-form').submit();
}
else return false
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$("#contact-form").off('submit').submit();
}
});
return false;
});
First, .promise().done(...) can be purged. As has been said, nothing asynchronous is going on.
That aside, the actual issue is most likely the repeated re-invocation of the submit handler.
Try a POJS (as opposed to jQuery) form submission :
if(formValid) {
this.submit();
}
Related
I have a function to test and make sure at least one form field is filled out:
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]');
var checked = checks_radios.filter(':checked');
var filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
And that is called when the form is submitted:
$(function(){
$('.checkThisForm').on('submit',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
/* ??? */
}
});
});
What goes in my else { } to allow the form to submit if the user has supplied at least one element to search for in the form?
return for form action will indicate to proceed or stop the submission
$('.checkThisForm').on('submit',function(e){
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
return false;
}
return true;
});
you are required to follow below info. First you need to triger click event and submit
$(function(){
$('.checkThisForm').on('click',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
this.submit();
}
});
I want to check on form submit that certain condition is satisfied before submitting the form
function checkConditions(e){
if ($('#someId').val() == '') {
console.log('value of #someId is empty');
e.preventDefault();
return false;
}
}
$('form').submit(function (e) {
checkConditions(e);
});
on form submit I'm getting print inside console that value is empty but form is sumbitted eitherway. What I'm doing wrong here?
Try this:
function checkConditions(){
if ($('#someId').val() == '') {
console.log('value of #someId is empty');
return false;
}
return true;
}
$('form').submit(function (e) {
if(!checkConditions()){
e.preventDefault();
return false;
}
});
I have a code snippet like this.When I submit it shows alert button and ajax function calls.How can I prevent.I have a textbox with id=id1.I need to call ajax only if there is a value in textbox.
I have also another button in same page so I need to call common validate function inside that button also.So I wrote common function.
$( document ).ready(function() {
function validate() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function() {
validate();
$.ajax...code goes here
});
});
If it is not valid, return from the click handler without executing the ajax call.
In your case you are calling the validate method but you are not doing anything with the value returned from it. So use a if condition to check whether it is true or false, if false then return from the click handler
$(document).ready(function () {
function validate() {
if ($('#id1').val() == '') {
alert('enter a value');
return false;
}
return true;
}
$('#button').click(function () {
if (!validate()) {
return;
}
$.ajax...code goes here
});
});
keep your functions out of jquery functions, to make it reusable across other places.
$( document ).ready(function() {
$('#button').click(function() {
var isValid = validate();
if(isValid){
$.ajax...code goes here
}
});
});
var validate = function() {
if($('#id1').val=='') {
alert('enter a value');
return false;
}
return true;
}
Return the validity of the check box and if it is true then trigger the ajax request.
I have a simple form with some form fields. Some of them are required some are not. The required field are required by adding the class 'required'.
When I submit I check the #contact-form fields and on the basis of there I give the empty field error classes and submit the form yes or no.
Adding the error classes to the fields is not a problem, but checking the "error" variable is. Because I don't know where I can check the error variable.
This is my jQuery code:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
JsFiddle
The following code should do what you want, just give your contact form submit button the id of #contact-form-button.
$('#contact-form-button').click(function(e) { // using click function
// on contact form submit button
e.preventDefault(); // stop form from submitting right away
var error = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
error = true;
}
});
if (!error) { // if not any errors
$('#contact-form').submit(); // you submit form
}
});
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
return false;
}
return true;
})
if validation cross successfully then it return true for submit the form
I found out that my code just works. The reason I thought it was not working, is because I was still using PHP handling my real website where I made 1 field required and in my jQuery not. This made the confusion.
So the following code works:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page
$('#loginAccount').submit(function() {
$(this).find(':input:text').each(function(i) {
if($(this).val()=="") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
return false;
}
});
});
$('#loginAccount').submit(function() {
var valid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val() == "") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
valid = false;
}
});
return valid;
});
You are currently returning from the each. What you need to do is track whether it's valid and then use that value as the return from your submit.
return false; takes on a different meaning inside of a jQuery each(). It is used to break out of the each. Maybe you could set a flag that is observed after the each() to see if the validation succeeded.
You need to return false in the submit function, not the each function:
$('#loginAccount').submit(function() {
var isValid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val()=="")
{
isValid = false;
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
}
});
return isValid;
});
May be you shoul use closure to return a value?
$('#loginAccount').submit(function() {
var result = true;
$(this).find(':input:text')
.each(function(i) {
if($(this).val()=="")
{
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
result = false;
}
});
return result;
})