Reputation: 135
I have a form that I am validating with jQuery, once validation is passed I want to submit the form:
$(document).ready(function(){
$('[name="form"]').submit(function(e){
e.preventDefault();
var one = $('[name="one"]');
var two = $('[name="two"]');
var three = $('[name="three"]');
var errors = [];
if(!one.val()){
errors.push(one);
}
if(!two.val()){
errors.push(two);
}
if(!three.val()){
errors.push(three);
}
if(errors.length > 0){
$.each(errors, function(i, v){
$(v).css('border', '1px solid red');
});
} else {
console.log('true');
$('#bmi-form').submit();
}
});
});
My idea was that the return true at the end would submit the form but it does nothing..
In the console I see the console.log('true');
So how can I submit the form on validation success... I dont want to use any plugins as it is a very small app and there is no need to bloat it.
Regards
Upvotes: 0
Views: 40
Reputation: 74738
As you are using e.preventDefault();
which stops the form to get submitted. Now you can .submit()
the form instead of return true;
:
} else {
console.log('true');
this.submit(); // return true;
}
or remove the e.preventDefault()
and change to this code to submit only when there are no errors:
if(errors.length > 0){
$.each(errors, function(i, v){
$(v).css('border', '1px solid red');
});
e.preventDefault(); // put e.preventDefault(); stop to submit incase of errors
} else {
console.log('true');
// just remove the return true; from here because if everything is
} // fine form will submit. Or you can just remove the else block.
Upvotes: 1
Reputation: 2432
You need to submit your form...
$("formid").submit();
$(document).ready(function(){
$('[name="form"]').submit(function(e){
e.preventDefault();
var one = $('[name="one"]');
var two = $('[name="two"]');
var three = $('[name="three"]');
var errors = [];
if(!one.val()){
errors.push(one);
}
if(!two.val()){
errors.push(two);
}
if(!three.val()){
errors.push(three);
}
if(errors.length > 0){
$.each(errors, function(i, v){
$(v).css('border', '1px solid red');
});
} else {
console.log('true');
$("formid").submit();
}
});
});
Upvotes: 0
Reputation: 7605
User $("form").submit(); if your data is in form or of dynamically validation is created then do ajax call; References
Upvotes: 0