Hyperlink entire row or cell using data-href attribute

Hyperlink entire row or cell using data-href attribute

haliorishalioris Posts: 9Questions: 2Answers: 0

I saw the example in the documentation for using a column renderer to make the value in the column a hyperlink. However I wanted to make the entire row or cell a hyperlink, not just the text within it (and not using css display). I was curious how you would go about making a row or column a hyperlink using jquery delegated events and the data-href attribute. I got this working by simply referring to the actual table data with the following:

var rankTable = $('#myTable').DataTable();
$('#myTable').on('click', 'tbody tr', function() {
  window.location.href = `someurl/${table.row(this).data()[1]}`;
});

but i would like to know how to go about adding the data-href attribute to a td or tr if i wanted to be able to do something like the following:

<tr data-href='someurl/1234'>
  <td>Cell Data</td>
</tr>
$('#myTable').on('click', 'tbody tr', function() {
  window.location.href = $(this).data('href');
});

I swore I saw an example somewhere about adding attributes to rows or cells but can't seem to find it now.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Answer ✓

    createdRow and columns.createdCell are the options that can be used to add attributes to rows / cells.

    Out of interest, what's the benefit of adding the attribute to the row instead of just reading it from the row's data?

    Allan

  • haliorishalioris Posts: 9Questions: 2Answers: 0

    Hey allan thanks for the response. There are case where I just want the user to be able to click anywhere in the row to get the detail and not have to click only on the text. Just a style thing more than anything but there are cases where I don't want all the text to look like hyperlinks and for the user to actually have to click the text when there may be a lot of whitespace. Here is an example table from my site where the entire row is a link.

  • haliorishalioris Posts: 9Questions: 2Answers: 0

    You can also see if you look at that page that I just used jquery event delegation to handle the row click along with changing the pointer. That was done witih the following:

      $('#rankTable').on('click', 'tbody tr', function() {
        window.location.href = `/rankings/team/${rankTable.row(this).data()[3]}/d1m`;
      });
      $('tr').css('cursor','pointer');
    

    If you think I should have done it differently let me know.

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    The only change I'd suggest is to move the CSS stuff into a stylesheet and mark your table with a class to apply the style against. If that isn't possible then use #rankTable tbody as the selector rather than tr.

    Allan

This discussion has been closed.