Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find same td in prev. and next row

Tags:

jquery

css

click

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');
        }
    });
});
like image 399
Slavak Avatar asked Mar 15 '12 18:03

Slavak


3 Answers

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');
like image 161
Slavak Avatar answered Oct 19 '22 04:10

Slavak


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

    });
});
like image 27
ShankarSangoli Avatar answered Oct 19 '22 06:10

ShankarSangoli


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.

like image 39
James Aylett Avatar answered Oct 19 '22 06:10

James Aylett