Reputation: 2585
I am trying to submit form with jQuery but sometime it hangs the browser and sometime it crash. I am using jQuery validate plugin and I want to submit form when validation get passed. Is it possible that I submit form normally after validation pass, I don't want to submit with jQuery
Here is my little code snippet.
var validate = function () {
$('#contactForm').validate({
rules: {
'first-name': {
required: true
},
'sur-name': {
required: true
}
},
submitHandler: function (form) {
$('#contactForm').submit();
return false;
}
});
};
$('#submitEnquiryForm').click(validate);
Upvotes: 3
Views: 1538
Reputation: 144729
That's because the validation passes (which listens to the submit event) and you trigger the submit
event again and again.
submit -> validate -> submit -> validate -> ... -> crash(maximum call stack size exceeded)
Try:
form.submit();
or:
$('#contactForm')[0].submit();
Which will submit the form normally and doesn't call the validate
method.
Upvotes: 5
Reputation: 737
You can use it instead of jquery.validate:
<style>
.error {
border: 2px solid red;
}
</style>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
</head>
<body>
<form id="contactForm" action="javascript:alert('submitted')">
<input type="text" id="first-name"/>
<input type="text" id="sur-name"/>
<input type="submit" />
</form>
</body>
<script>
$('#contactForm').submit(function (event) {
fname = $('#first-name');
sname = $('#sur-name');
if (!fname.val())
{
fname.addClass('error');
event.preventDefault();
}
else
{
fname.removeClass('error');
}
if (!sname.val())
{
sname.addClass('error');
event.preventDefault();
}
else
{
sname.removeClass('error');
}
});
</script>
Upvotes: 1
Reputation: 2481
As I understand, your code when you click #submitEnquiryForm
validate #contactForm
and submit it. ¿ok?
submitHandler
function is called when you submit the form so you are in an infinite loop; submit event triggers submit again.
You don't need de call to submit
in submitHandler
.
I think it must be:
$('#contactForm').validate({
rules: {
'first-name': {
required: true
},
'sur-name': {
required: true
}
}
});
$('#submitEnquiryForm').click(function(){
$('#contactForm').submit();
});
That validate the form when submit event is triggered, if you want to use click on #submitEnquiryForm
instead of its submit buttom. The submitHandler
function is for other purpouses as if you want to do other operations or tests before submit.
Upvotes: 0
Reputation: 15403
use .Off() event in jquery. The .off() method removes event handlers that were attached with .on().
$('#submitEnquiryForm').off("click").on("click" , validate);
Upvotes: 0