How to traverse table in Jquery and add a class?

Posted by SWL on Stack Overflow See other posts from Stack Overflow or by SWL
Published on 2012-06-26T15:06:29Z Indexed on 2012/06/26 15:16 UTC
Read the original article Hit count: 223

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-validate