jquery loop for script

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

I'd like to run script for each field which id begins with "imie" and ends with numbers 1 to 10. Each field "imie" depends on field "nazwisko" with the same number at the end eg. "imie6" depends on "nazwisko6".

$(document).ready(function () { $('#nowikons_dodaj').validate({ rules: {     imie1: {         required: {             depends: function (element) {                 return $("#nazwisko1").is(":filled");             }         }     } } }); }); 


Here's also html/php code for these fields:
for ($i = 1; $i <= 10; $i++) { echo "<tr><td>".$i."</td>"; echo "<td><input type='text' name='nazwisko".$i."' id='nazwisko".$i."'></td>"; echo "<td><input type='text' name='imie".$i."' id='imie".$i."'></td>";}

回答1:

If you colud give class name to imie element which is same as the id of nazwisko element, it would be easy. Then the code will be

$("[id^=imie]").change(function () {  alert($("." + this.id).val());  }); 

HTML

<td><input type='text' name='nazwisko1' id='nazwisko1'></td> <td><input type='text' class="nazwisko1" name='imie1' id='imie1'></td> 


回答2:

You'd be better off putting a validation function on the blur event of those fields. For example

$('#thatTable').on('blur', 'input.imie', function(evt) {     var nazwisko = $(this).parent(td).prev('td').find('input.nazwisko');     //now do so something with nazwisko's data }); 

This assumes you add a CSS class to each field to help the jQuery selector.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!