I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#commentForm").validate(); }); function addInput() { var obj = document.getElementById("list").cloneNode(true); document.getElementById('parent').appendChild(obj); } </script> <form id="commentForm" method="get" action=""> <p id="parent"> <input id="list" class="required" /> </p> <input class="submit" type="submit" value="Submit"/> <input type="button" value="add" onClick="addInput()" /> </form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs? Thank you...
FWIW, you could just call validate once on document. ready, and then do your rules adding within the addInput function. If you want to show that validation is succeeding/failing, attach handlers to submitHandler and invalidHandler . Yes, that might work, you need to add the rule for the last added input, like $('input.
In ASP.NET 3.5 a DynamicValidator was added. It basically "Enforces and catches exceptions that are thrown in a data model and displays the error."
Just use: $("input:empty"). length == 0; If it's zero, none are empty.
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript"> $(document).ready(function() { var numberIncr = 1; // used to increment the name for the inputs function addInput() { $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />')); numberIncr++; } $('form.commentForm').on('submit', function(event) { // adding rules for inputs with class 'comment' $('input.comment').each(function() { $(this).rules("add", { required: true }) }); // prevent default submit action event.preventDefault(); // test if form is valid if($('form.commentForm').validate().form()) { console.log("validates"); } else { console.log("does not validate"); } }) // set handler for addInput button click $("#addInput").on('click', addInput); // initialize the validator $('form.commentForm').validate(); }); </script>
And the html form part:
<form class="commentForm" method="get" action=""> <div> <p id="inputs"> <input class="comment" name="name0" /> </p> <input class="submit" type="submit" value="Submit" /> <input type="button" value="add" id="addInput" /> </div> </form>
Good luck! Please approve answer if it suits you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With