Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a table row (tr) clickable with jQuery (with an a href link, and hover!?)

Just a (hopefully) quick question, I have the following HTML code:

<tr>
 <td><img src="img/icons/file_pdf.png"></td>
 <td><a href="../upload/1267473577.pdf">Bulletin 1st March 2010</a></td>
 <td>(01/03/10)</td>
</tr>

Ideally I'd like a way to grab the a href link using jQuery and make it so that no matter where you click on that particular table row, it will take you to that link.

Is there any way to do this? I can do it via icky inline JavaScript as an absolute last resort, but since finding out about jQuery I quite like the idea of being able to do this cleanly and unobtrusively :-)

like image 696
Nick Avatar asked Mar 03 '10 23:03

Nick


People also ask

How do you make a whole row in a table clickable as a link?

To make the entire row as clickable in this case, one can use a link <a> tag to wrap its content.

How do you make a tr tag clickable?

You can use onclick javascript method in tr and make it clickable, also if you need to build your link due to some details you can declare a function in javascript and call it in onclick, passing some values.

How do you link a table to data in HTML?

Solution 1: Use JavaScript JavaScript can be used to programmatically navigate a user to another page when a table row is clicked. There are many ways to do this with JavaScript, but one way is to add an event listener on every table row element and use window. location. href to navigate the user to another page.


2 Answers

I found this solution to work well for me.

$('table tr').live("click",function(e){ 
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLAnchorElement){
        return;
        }
        alert('works');
});
like image 87
Scott Yu - builds stuff Avatar answered Sep 24 '22 03:09

Scott Yu - builds stuff


Assuming it's a "normal" link (not a Javascript trigger) this will be sufficient:

$("tr").click(function() {
  window.location.href = $(this).find("a").attr("href");
});

You will probably want to communicate this behaviour to the user in some way. The minimal approach would be changing the cursor while hovering over the row.

like image 27
cletus Avatar answered Sep 24 '22 03:09

cletus