Search code examples
jqueryrowsclickable

How to make the entire row in a table clickable as a link, except the last column?


I managed to get the rows in my table to be clickable and linked to the href attribute of the <a> element. However I started to have issues when I made the selector only select the rows except the last column.

With the below code the clickable row is only active for the entire row except the last cell which is what I require as I have administrative links in this cell (links to activate, edit, delete etc rows). The only problem is that no matter which row you click on it sends you to the link in the very top row. I think this has something to do with my selector for the find('td a') but I can not figure it out.

$('#dataTable tr td:not(:last-child)').click(function () {
    location.href = $('#dataTable tr').find('td a').attr('href');
});  

The hover works great and only changes the pointer if the mouse is over any cell except the last column.

$('#dataTable tr td:not(:last-child)').hover(
    function() { 
        $(this).css('cursor','pointer');
    },
    function() {
        $(this).css('cursor','auto');
    }
);

Solution

  • It is because you are getting all the tr's in the table and then the first anchor that is found will be returned, try changing it like this:

    $('#dataTable tr td:not(:last-child)').click(function ()    {
     location.href = $(this).parent().find('td a').attr('href');
    });
    

    what it means is it will get the clicked element $(this) as a jquery object, and then go to its parent. (the row element).