Traversing td/tr with jquery's closest()

rashcroft3 picture rashcroft3 · Oct 14, 2009 · Viewed 22.8k times · Source
<td width="162"><span class="required">*</span> Name:</td>
<td width="407">
    <label>
        <input id="store_name" class="text_field alnum" type="text" minlength="3"
        maxlength="30" size="40" name="store_name" style="color: rgb(51, 51, 51);"/>
    </label>
</td>
<td class="char_count_area" style="color: green;"/>

I have some jQuery code that goes like this:

$('.text_field').each(function(){
        $(this).keyup(function(){                 
            $(this).parent().parent().parent().find('.char_count_area').html(remainingChars); 
....

As you can see, I'm trying to reach char_count_area from text_field in a rather inefficient manner. It works, but it goes crazy if I alter the table design slightly. I've tried using

$(this).closest('.char_count_area').html(remainingChars)

but it doesn't work (characters don't appear).

How can I achieve this using closest ?

Answer

Russ Cam picture Russ Cam · Oct 14, 2009

I've tidied your code somewhat (removed the each() as it's not needed and better qualified your selector. Using just CSS classes is not best practice, specifying an element name too will be more performant).

$('input.text_field').keyup(function(){                                 
    $(this).closest('td').next().html(remainingChars);
});

bear in mind that closest() was added in jQuery 1.3, so if you're using an older version of jQuery then you might want to use

$('input.text_field').keyup(function(){                                 
    $(this).parent().parent().next().html(remainingChars);
});

This will be fine, so long as the <input> remains in an element in a <td>, and the next <td> is the one with CSS class char_count_area

EDIT:

In response to your comment, here's a better solution that relies less on DOM positions

('input.text_field').keyup(function(){                                 
    $(this).parents('tr:first').find('td.char_count_area').html(remainingChars);
});