Reputation: 323
I have a table and I know how to search next and prev TD
, but how to do it on the next and previous TR
?
012
345 <- example, I clicked on 4, it checks 3 and 5, but how to check on 0,1,2 and 6,7,8?
678
$(document).ready(function() {
$("td").click(function() {
var x = $(this).next().css('backgroundColor');
var y = $(this).prev().css('backgroundColor');
if (x == 'rgb(255, 0, 0)' || y == 'rgb(255, 0, 0)') {
return;
} else {
$(this).css('backgroundColor', 'red');
}
});
});
Upvotes: 8
Views: 10488
Reputation: 323
I made some research and came up with a working solution that works. Thanks all for help:
$(this).parent().next().find('td').eq($(this).index()-1).css('backgroundColor');
Upvotes: 10
Reputation: 69915
Use parent()
method on td
to go to tr
and then you can use prev()
or next()
accordingly.
$(document).ready(function() {
$("td").click(function() {
var $tr = $(this).parent();//this will give the tr
$tr.prev();//previous tr
$tr.next();//next tr
//To get the corresponding td's in the next and prev rows
var tdIndex = $(this).index();
$tr.prev().find("td:not(:eq(" + tdIndex + "))");
$tr.next().find("td:not(:eq(" + tdIndex + "))");
});
});
Upvotes: 4
Reputation: 13597
$(this).parent('tr').next()
and
$(this).parent('tr').prev()
Upvotes: 2
Reputation: 3372
Something like $(this).closest('tr').next('tr').find('td')
will get you all the <td>
s within the row after the one containing the <td>
your event fired on.
Upvotes: 3