Creating rules efficiently for large forms
I'm using the jQuery validate plugin to validate a form with a lot of fields:
<td><input name="first_name0"></td>
<td><input name="last_name0"></td>
<td><input name="age0"></td>
<td><input name="first_name1"></td>
<td><input name="last_name1"></td>
<td><input name="age1"></td>
<td><input name="first_name2"></td>
<td><input name="last_name2"></td>
<td><input name="age2"></td>
...
<td><input name=开发者_如何学编程"first_name200"></td>
<td><input name="last_name200"></td>
<td><input name="age200"></td>
What's the best way to add validation rules to all of the identical fields? Currently I'm adding rules like this, however it's very slow after 100 rows.
$("input[name*=age]").each(function(i) {
$(this).rules("add", {
digits: true
});
});
$("input[name*=first_name], input[name*=last_name]").each(function(i) {
$(this).rules("add", {
digits: true
});
});
There's no need to loop, it'll operate on a Query set, like this:
$("input").filter("[name*=age], [name*=first_name], [name*=last_name]")
.rules("add", {
digits: true
});
Giving them a class would be a bit more maintainable, for example:
<td><input name="first_name0" class="digits"></td>
<td><input name="last_name0" class="digits"></td>
<td><input name="age0" class="digits"></td>
Then you could do this:
$("input.digits").rules("add", {
digits: true
});
精彩评论