tags:

views:

44

answers:

3

I have a table with multiple rows, and each row contains three cells. Each cell contains a textbox, so it looks like this:

XXXX   XXXX   XXXX

on the keyup event of the first textbox, I want its contents to be copied into the second textbox, but not the third textbox.

my keyup event I can get a reference to the first textbox. Doing .parent() will give me the cell, and if I want, doing .parent() again will give me the row.

What JQuery can I use to get the adjacent textbox?

+4  A: 

You can use .next() to get the next sibling, like this:

var nextTD = $(this).closest("td").next();
//for your case:
$(this).closest("td").next().find("input").val($(this).val());

.parent() works too, .closest() is just a bit more flexible, for you could change your markup and it'd still go to the nearest <td> parent.

Nick Craver
closest...wow...is there anything these JQuery people haven't thought of? :)
SLC
@SLC - The DOM traversing is a pretty strong area for the library, there are *many* functions for moving around, take a look here: http://api.jquery.com/category/traversing/tree-traversal/
Nick Craver
It seems that closest('td') is returning null I am not sure why...
SLC
@SLC - that shouldn't be the case...which version of jQuery are you using? If it's an older version, stick with `.parent()` for now, or `.parents("td:first")` for the same effect in pre-1.4 versions of jquery.
Nick Craver
+1  A: 

From the .parent() <td>, use next() to go to the next <td>, then .children('input') to get the child <input> element.

So you end up with something like this in your keyup handler.

$(this).parent().next().children('input').val( this.value );
patrick dw
A: 

Give the [next()][1] function a try. This selects the next sibling of the selected element.

Tim S. Van Haren