tags:

views:

4182

answers:

3

What is the best way to make a tables row a link? I currently am using jquery to zebra stripe the rows and also to highlight the onmouseover/off selected row so if js is the answer please use jquery.

+1  A: 

Register a onclick event handler for the tr element. Something like this using jQuery:

$("tr").bind("click", function(){ 
  window.location = 'http://www.example.com/'; 
});
Ronny Vindenes
Doesn't this link you to the same location on every row click?
Zaagmans
You may use a hidden input in each tr to store the url.
Adones Cunha
This will indeed bind the same link to each row, modify according to your needs..
Ronny Vindenes
+5  A: 
$(document).ready(function(){
   $("tr").click(function(){
      /* personally I would throw a url attribute (<tr url="http://www.hunterconcepts.com"&gt;) on the tr and pull it off on click */
      window.location = $(this).attr("url");

   });
});
hunter
+12  A: 

I just use css:

<style>
table.collection {width:500px;border-collapse:collapse;}
table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;}
table.collection tr:hover {background-color:#ffe;}
table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:0px;}
table.collection td a {text-decoration:none; display:block; padding:0px; height:100%;}
</style>
<table class="collection">
<tr>
    <td><a href="#">Linky1</a></td>
    <td><a href="#">Data1</a></td>
</tr>
<tr>
    <td><a href="#">Linky2</a></td>
    <td><a href="#">Data2</a></td>
</tr>
</table>
Nick
Best solution by far. Browser still see's this as a link so 'open in tab' or 'copy link' will work. The other solutions break my browser! There is scope for a JQuery solution that automates the above by DOM manipulation.
andybak
I'm having trouble with this solution. If one of the table cells contains enough content to wrap lines, the height of neighbouring cells won't stretch to the full height. Have you found a workaround for this case?
troelskn
This sounds like an IE quirks mode issue. I don't see this in firefox or IE 7-8 with "-//W3C//DTD XHTML 1.0 Strict//EN". It also may not work in IE 6 (but what does?)
Nick
on second thought - adding height:100%; to the a style would most likely fix it (see the last edit).
Nick
height:100% doesn't fix it for me in FF 3.6, HTML5 doctype.
Simon D