HTML Row Click

On a recent project I wanted my tables row to be clickable, so a user could click on a row and perform a default action. This action could be to edit the details of the row item. For example, if a user wants to edit a row they could the click edit link, but also click anywhere else on the row (except for the other links).

TableClick

To achieve this I used the following JavaScript (which requires JQuery):

$(".tablerowclick td:not(:last-child)").click(function () {
   var defaultAction = $(this).parent().find("a[data-defaultaction='true']");
   if (defaultAction) {
     location.href = defaultAction[0].href;
   }
 }).css('cursor', 'pointer');

The JavaScript looks for an anchor tag / link which has a data attribute of defaultaction set to true. It uses the URL of this anchor tag / link as the default action when the row is clicked. In addition to this it changes the cursor to a pointer to make it more obvious that the row is clickable.

I then added the ‘tablerowclick’ class to the table:

<table class="tablerowclick">

And then finally I had to decorate the link that I wanted to be the default action with the a data tag:

<a data-defaultaction="true" href="/user/Edit/2">Edit</a>

The full example code is:

<table class="tablerowclick">
 <thead>
   <tr>
     <th>Id</th>
     <th>FirstName</th>
     <th>LastName</th>
     <th>JobTitle</th>
     <th></th>
   </tr>
 </thead>
 <tbody>
 <tr>
   <td>1</td>
   <td>John</td>
   <td>Smith</td>
   <td>Account manager</td>
   <td>
     <a data-defaultaction="true" href="/user/Edit/1">Edit</a> |
     <a href="/user/Details/1">Details</a> |
     <a href="/user/Delete/1">Delete</a>
   </td>
 </tr>
 <tr>
   <td>2</td>
   <td>Fred</td>
   <td>Bloggs</td>
   <td>Sales manager</td>
   <td>
     <a data-defaultaction="true" href="/user/Edit/2">Edit</a> |
     <a href="/user/Details/2">Details</a> |
     <a href="/user/Delete/2">Delete</a>
   </td>
 </tr>
 </tbody>
</table>

 $(".tablerowclick td:not(:last-child)").click(function () {
   var defaultAction = $(this).parent().find("a[data-defaultaction='true']");
   if (defaultAction) {
     location.href = defaultAction[0].href;
   }
 }).css('cursor', 'pointer');

Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me