How to traverse table in Jquery and add a class?
- by SWL
I have a simple table of two rows. The first column is required, but the others are not; however, I would like them to be required in pairs. So if the user enters a value for Quantity3, then Size3 should also now be required.
As a fiddle: http://jsfiddle.net/NaRts/7/
<tr>
<td><input name="qty1[492]" class="qty required" type="text"></td>
<td><input name="qty2[492]" class="qty" type="text"></td>
<td><input name="qty3[492]" class="qty" type="text"></td>
</tr><tr>
<td><input name="size1[492]" type="text" class="size required" ></td>
<td><input name="size2[492]" type="text" class="size" ></td>
<td><input name="size3[492]" type="text" class="size" ></td>
</tr>
And the simple jQuery I have is:
$('.qty').keyup(function() {
var s = $(this).attr('name'); // = qty3[418]
var qtyID = s.replace(/[^1-9\[\]]/g, ""); // = 3[418]
var SizeID = "size" + qtyID;
var $sizeInput = $(this).closest('tr').next().find(SizeID);
$sizeInput.css('background-color', 'green');
$sizeInput.addClass('required');
//I tried this too but it didn't work
//$(this).parent().find(SizeID).addClass('required');
});?
?
Any help is much appreciated.