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>
.....
To make the entire row as clickable in this case, one can use a link <a> tag to wrap its content.
You need an a element to make a link, and you can't wrap an entire table row in one. The closest you can get is linking every table cell. Personally I'd just link one cell and use JavaScript to make the rest clickable.
The key is to use stretched-link on the text within the cell and defining <tr> as a containing block. You can define containing block in different ways for example setting transform to not none value (as in example above).
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;
}
});
});
});
alternatively, you might use event.stopImmediatePropagation()
in the last col button event handler.
$('#movies tr').click(function () {
var href = $(this).find("a").attr("href");
if(href) window.location = href;
});
$('#movies input:button').click(function (e) {
// button's stuff
e.stopImmediatePropagation();
});
the advantage (or inconvenient) is that is allow you to click around the button in the last cell. (in the margin padding). I can be an inconvenient, as button miss click would open the linked page and surprise the user.
Another alternative can be to use only one event handler, which decide action to do with event.which. It is my favorite method as it limits the number of event handlers. the use of delegate is for the same reason. One handler by table, instead of one by row.
$('#movies').delegate('tr', 'click', function (e) {
if ( $(e.target).is('input:button') ) {
// button's stuff
}
else {
var href = $(this).find("a").attr("href");
if(href) window.location = href;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With