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

3

8

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');
    }
);
Abominate answered 23/9, 2011 at 6:30 Comment(0)
B
12

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

Bumptious answered 23/9, 2011 at 6:36 Comment(1)
Thanks so much. I have been trying to get this to work all night. I am new to jquery and figured i was grabbing all the tr's, I just could not figure out how to change it. Thanks again!Abominate
W
1
$('#dataTable tr td:not(:last-child)').click(function ()    {
 location.href = $(this).parent().find('td a').attr('href'); 
});  

I think this should work. Your code always takes the href from the first "td a" it finds inside your dataTable. This code takes the a it finds in the specific td you are looking for.

Warehouse answered 23/9, 2011 at 6:37 Comment(0)
V
0

Alternative answer.

HTML:

<table>
  <tbody>
    <tr data-href="#">
      <td>first</td>
      <td>second</td>
      <td>
        <div class="dropdown">...</div>
      </td>
    </tr>
  </tbody>
</table>

JS:

jQuery(document).ready(function ($) {
  $("tbody").on('click', 'tr td:not(:last-child)', function () {
    window.location = $(this).parent().data("href");
  });
});
Voltaism answered 17/3, 2020 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.