NibblyPig
NibblyPig

Reputation: 52932

In JQuery how can I get the adjacent table cell?

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?

Upvotes: 16

Views: 19217

Answers (3)

user113716
user113716

Reputation: 322462

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 );

Upvotes: 3

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 37

Related Questions