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

3 Answers 3

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

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!
    – Andrew
    Sep 23, 2011 at 6:40
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.