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-defaultaction=”true” 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>

src="/lib/jquery/dist/jquery.js"> 


 $(".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');

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s