Search code examples
jqueryhtml-tableclickable

jQuery: Making entire table row a link, apart from one column


I have a script which can make each table row clickable (as a link), however I need the last column to remain untouched as this column as an 'edit' button. Can anyone help me amend the script so it'll work?

Here the jQuery so far:

$(document).ready(function() {
  $('#movies tr').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});

Here's the HTML for one row:

<table id="movies">
  <tr class='odd'>
    <td>1</td>
    <td><a href='/film.php?id=1'></a>Tintin</td>
    <td>Tintin and Captain Haddock set off on a treasure hunt for a sunken ship.</td>
    <td><a href='/edit.php?id=1'>edit</a></td>
  </tr>
  .....

Solution

  • you need to go one step deeper and control the tr's elements, bind a click handler to each td which is not the last in the tr:

    $(document).ready(function()
    {
       $('#movies tr').each(function(i,e)
       {
          $(e).children('td:not(:last)').click(function()
          {
             //here we are working on a td element, that's why we need
             //to refer to its parent (tr) in order to find the <a> element
             var href = $(this).closest("tr").find("a").attr("href");
             if(href)
             {
                window.location = href;
             }              
          });
       });
    });