How to add hyperlink to table row <tr> ?


If you having a table with its table row <tr> generating in a loop to form multiple rows.


If you  want to give separate <a> link to each <tr>. Since in table we can add only add data to <td> only, you are not able to achieve that.



There is a way to achieve it which is following.


Html:
<table>
    <tr href="http://myspace.com">
      <td>MySpace</td>
    </tr>
    <tr href="http://apple.com">
      <td>Apple</td>
    </tr>
    <tr href="http://google.com">
      <td>Google</td>
    </tr>
</table>

JavaScript using jQuery Library:
$(document).ready(function(){
    $('table tr').click(function(){
        window.location = $(this).attr('href');
        return false;
    });
});

You can view this here: http://jsbin.com/ikada3/88
To get source right click on webpage and view source code.

Making a full row clickable is useful when you show records in a table, for example a list of customers, orders or students. Instead of clicking only on one small link in a cell, the user can click anywhere on the row and open the detail page. This makes the table easier to use, especially on touch screens and small displays.

One thing to remember: if a row already contains real links or buttons, for example a delete button, clicking those should not open the row link, so always test this case after applying the code. Also, keyboard users cannot click a row the way mouse users do, so keep at least one normal link inside the row for accessibility. You can also read my related post about how to open external links in a new window using jQuery, which works well together with this technique.

Comments