views:

215

answers:

1
<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 ?

+1  A: 

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);
});
Russ Cam
ok thanks. one issue - occasionally i have another <td> BEFORE char_count_area, so next(); never reaches char_count_area, i'd have to use next().next().. I'm hoping to use the same javascript code universally. This is why I was trying to specifically designate the closest '.char_count_area', rather then any 'td'. Any help?
rashcroft3