JQuery validation for an array of input elements

I need to check an array of input text elements (mileage): For example:

<tbody> <c:forEach items="${list}" var="item"> <tr> <!--some other columns---> <td align="left"><input type="text" name="mileage" value="" /></td> </tr> </c:forEach> </tbody> 

The script to check is:

 $(document).ready(function(){ $("#form1").validate({ rules: { mileage: { required: true } }, submitHandler: function(form) { form.submit(); } }); }); 

Now the problem is that .validate.js only checks the first element of the run. What can I do? How can I get the plugin to check all input text?

I hope you can help me.

+7
source share
3 answers

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(); } 
+8
source

Based on eddy, this function also takes into account ignore settings.

  checkForm: function() { this.prepareForm(); for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { var checkingElements = this.findByName( elements[i].name ).not(this.settings.ignore); if (checkingElements.length !== undefined && checkingElements.length > 1) { for (var cnt = 0; cnt < checkingElements.length; cnt++) { this.check( checkingElements[cnt] ); } } else { this.check( elements[i] ); } } return this.valid(); }, 
+4
source

In these cases, you need to run a loop:

 $(document).ready(function() { $("#form1").validate({ submitHandler: function(form) { form.submit(); } }); $("#form1 input[name='mileage']").each(function() { $(this).rules("add", { required: true }); }); }); 

.rules() only affects the first match, so you need .each() to scroll and add any rules to all matches.

+3
source

All Articles