Private Social Media
Had it with Facebook and Twitter?

Try out 'Friends and Family' - FnF, an alternative system for use by private groups.

Mobile friendly.

Simple installation designed to work with shared hostings.

No advertising, no annoying notifications.

Demo available here.

Getting Started with Datatables - Select a Row

If you're reading this then you are presumably already including jquery.js in your pages, so you might also be interested to read my notes on Getting Started with jQuery Plugins.


Having started on this Datatables tack I thought I'd add something that I wanted to do, and struggled with for some time. It might be useful to others.

The objective is to be able to select and highlight a row. Presumably one might at that point also want to know the selected row values. This add on will begin with dt105.html from my previous article

It is not that complicated once you know how, but in this case it is "Some Coding Required."

Nitty Gritty.

The first thing we need to do is to attach a click event handler to our table rows. The trick here is to use the jQuery delegate method on the table body:

$(function() {
   $('#mytable').dataTable( {});
   $('#mytable tbody').delegate("tr", "click", rowClick);

Then we need to provide the rowClick function. I have used a global variable here out of lazyness. I'll leave it to the reader to put it in a favorite safe place.

var hlr = 0;   // Reference to the currently highlighted row

function rowClick()
   if (hlr)
      $("td:first", hlr).parent().children().each(function(){$(this).removeClass('markrow');});
   hlr = this;
   $("td:first", this).parent().children().each(function(){$(this).addClass('markrow');});

   // You can pull the values out of the row here if required
   var a = $("td:first", this).text();
   var b = $("td:eq(1)", this).text();
   alert("One = "+a+", Two = "+b);
Since we're adding a class to each cell of the selected row, there's 'Some Styling Required' too - very little:

.markrow { background-color:#ffbba9 !important; }
The '!important' qualification on the background-color is important. If you're working with a table where the rows already have a background color, as in odd/even striping, then the markrow styling may not prevail over the existing styling.

The rowClick function illustrates how you can pull values out of the row at the time of the click. You can see the result in dt106.html .

Hope this is useful.