Reputation: 141
I have a form that creates it's input fields dynamically. It was working great but now I need to call a function when the form is valid. My problem is that as soon the form is loaded the submitHandler
triggers. I verified it by adding alert("alert")
inside the submit handler.
<input type="text" id="FName" name="FName" class = "vali" /> //these input fields are for demonstration; these are created dynmaiclly
<input type="text" id="SName" name="SName" class = "vali"/>
<button type="button" id="submit" name="submit"> //have tried type="submit" as well
</button>
<script type="text/javascript">
$(document).ready(function () {
$('.vali').each(function () {
$(this).rules('add', {
required: true,
messages: { required: "Can't be empty" },
submitHandler: function (form) {
alert("alert"); // this fires as soon as the page load.
}
})
});
});
</script>
Upvotes: 0
Views: 2246
Reputation: 98728
The submitHandler
is a callback function of the .validate()
method (the initialization method of the plugin). It's an option assigned to the whole form's behavior, never assigned to an individual field.
The submitHandler
...
can never be used inside of the .rules()
method. Only the individual rules and the messages
option can be inside of the .rules()
method.
can never be used inside of the rules
option of the .validate()
method.
can only be used inside of the .validate()
or .setDefaults()
methods.
Proper usage...
$(document).ready(function () {
$('#myform').validate({ // initialize plugin
submitHandler: function (form) {
// fires on a VALID form just after the submit button click event.
alert("alert");
}
});
});
OR
$.validator.setDefaults({ // change default options
submitHandler: function (form) {
// fires on a VALID form just after the submit button click event.
alert("alert");
}
});
Since .setDefaults()
needs to be called before .validate()
, you could pull it out of the DOM ready event handler to force this to happen.
DEMO: http://jsfiddle.net/yvj202aL/
Upvotes: 2