Reputation: 4413
I need to dynamically add validation rules to a text box when the user clicks on the checkbox in that row and remove it when the user unchecks it. This is what I did, and it works fine, but I'm not sure if it is the right way to do it. Here's my html code:
<tbody>
<c:forEach items="${list}" var="item">
<tr>
<td align="center">
<input type="checkbox" name="selectItems" value="<c:out value="${item.numberPlate}"/>" />
</td>
<td align="left"><c:out value="${item.numberPlate}"/></td>
<td align="left"><c:out value="${item.driver.fullName}"/></td>
<td align="left"><input type="text" name="mileage_<c:out value="${item.numberPlate}"/>" value="" /></td>
</tr>
</c:forEach>
</tbody>
and my jquery:
-----EDITED----
Now I'm using add/removeClass and it also works fine,but isn't there a quicker way of doing this? I mean , one way to avoid writing so many 'add/removeClass' instructions? and finally how could I indicate "min:100" or " minlength:6" with addClass?
$("input[name=selectItems]").change(function() {
if (this.checked)
{
$(this).closest("tr").find("input[name^=mileage]").addClass('required');
$(this).closest("tr").find("input[name^=mileage]").addClass('number');
}
else
{
$(this).closest("tr").find("input[name^=mileage]").removeClass("required")
$(this).closest("tr").find("input[name^=mileage]").removeClass('number');
}
});
any suggestion is welcome and... I almost forgot, Merry Xmas!
Upvotes: 0
Views: 5504
Reputation: 82903
One small improvement would be to use addClass and removeClass instead of assigning class values using attr so that you would not remove any classes already assigned to the input fields that don't deal with validation (i.e. classes assigned to style the fields)
Edit: : (Updated the code below as per your comments)
$("input[name=selectItems]").change(function() {
var me = $(this);
var scoper = me.parent().parent();
var otherInputs = $("input[name^=mileage]", scoper);
if (this.checked)
{
otherInputs.addClass('required number');
otherInputs.attr('maxlength', '6');
}
else
{
otherInputs.removeClass("required number");
}
});
Upvotes: 2