Hyperlink entire row or cell using data-href attribute
Hyperlink entire row or cell using data-href attribute
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
createdRow
andcolumns.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
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.
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:
If you think I should have done it differently let me know.
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 thantr
.Allan