Reputation: 99
To validate a form, I use a validation plugin. Example:
$ ( '# post-form').validator()
I would like to load the plugin on a form that is dynamically created via an Ajax return. What I try:
$ (document).on ('ready', '# post-command-detail').validator ();
But it does not work. How can I activate the validator on a form created 100% dynamically?
To know: # post-command-detail is the id of the concerned form.
Upvotes: 0
Views: 48
Reputation: 13801
You can do something like this, Just call validate after you render the html into element:
$(document).ready(function () {
validateForm("#form");
//once your ajax succeeded you can do something like this
$('#dynamicForm').html('<form id="form1" method="post" action="#"> <label for="name">Name</label> <input type="text" name="name" id="name" /><button type="submit">Submit</button> </form>');
validateForm("#form1");
});
function validateForm(form){
$(form).validate({
rules: {
"name": {
required: true,
minlength: 5
},
},
messages: {
"name": {
required: "Please, enter a name"
},
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<button type="submit">Submit</button>
</form>
<div id="dynamicForm" >
</div>
Upvotes: 0
Reputation: 11750
You can initialize the plugin inside the ajax callback, right after the new form creation:
$.ajax({
...
success: (data: any): void => {
if (data) {
// Append new form
$('body').append($('<form id="post-command-detail" />'));
// Select the new form and init the plugin
$('#post-command-detail').validator();
}
}
});
Upvotes: 0