Sometimes we need to check an array of input elements: for example -
<form name="signupForm" class="cmxform" id="signupForm" method="get" action=""> <select name="category[]" id="cat_1"> <option value="">Select One</option> <option value="1">aa</option> <option value="2">bb</option> <option value="3">cc</option> <option value="4">dd</option> </select> <select name="category[]" id="cat_2"> <option value="">Select One</option> <option value="5">ee</option> <option value="6">ff</option> <option value="7">gg</option> <option value="8">hh</option> </select> <select name="category[]" id="cat_3"> <option value="">Select One</option> <option value="9">ii</option> <option value="10">jj</option> <option value="11">kk</option> <option value="12">ll</option> </select> <input class="submit" type="submit" value="Submit"> </form>
Now we will use the jquery validation jquery.validate.js plugin to validate the form. The condition is that the user will have to choose a category from each drop-down list. The script for verification will be lower:
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { </script>
Now the problem is that readymade jquery.validate.js only checks the first element of the category []. Therefore, we need to change it a little.
In jquery.validate.js we can find a function called checkForm, we must change it as shown below:
checkForm: function() { this.prepareForm(); for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) { if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) { for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) { this.check(this.findByName(elements[i].name)[cnt]); } } else { this.check(elements[i]); } } return this.valid(); }
I just got this solution from http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/ I hope this helps someone.
Amit Jul 10 '14 at 7:43 2014-07-10 07:43
source share