jQuery: Bind an onClick Event to an Item in a DataTables Row

As it has quickly become apparent on this site, my two current favourites in the land of web development is the fantastic jQuery javascript library and the brilliant jQuery-based DataTables plugin that gives you instant dynamic table features applied to any bog standard HTML table.

The problem that I’m solving today arose from my desire to include a positive/negative flagging system to data being displayed in a DataTables view. So in each data row I added a column that contained both a greyed out happy and sad smiley face, on which the user will be able to click in order to color the appropriate face and thus indicate a state for that particular row of data.

The idea is simple enough. Click on the smiley face and the script will then fire off an ajax post to a script handler which will fiddle in the database and return the correct state which in turn changes the image accordingly – pretty standard AJAX stuff in other words.

However, herein lay the problem.

Because the DataTables was being fed through a server-side script, in other words the actual table data is loaded by the DataTables plugin itself, my jQuery function that was supposed to interact with the clicking of a smiley face couldn’t work because the elements it was meant to interact with simply didn’t exist when the page’s initial DOM tree was being loaded.

So how to solve this?

Well the solution obviously lies in binding the newly created elements to my existing click handler function, but the question remains – how exactly does one do this if the table data is being loaded through a jQuery function?

Well the answer lies with the DataTables-provided callback function entitled fnDrawCallback, which is called on every ‘draw’ event – in other words the perfect little hook to attach your jQuery code, which is to interact with the DataTables-loaded DOM data, to.

So how does one use this callback functionality then? Well the magic all gets stuffed into the DataTables constructor function. First, we declare the function that is to be run on the click event happening. Then, we bind this function to the click event for the desired elements in the standard jQuery manner. And then for the crucial point, this binding is done as part of the fnDrawCallback declaration in your dataTable constructor call.

So let’s see this in action:

//onClick handler function
function flagsmileysadclick()
{
        $(this).load('ajax_set_smiley_flag.php',{'smileyid':$(this).attr('id')});
}
 
//DataTables constructor
oTable = $('#commentstable').dataTable({
"bProcessing": true,
"bServerSide": true,
"iDisplayLength": 50,
"bLengthChange": false,
"sAjaxSource": "datatables_comments_list.php",
"sPaginationType": "full_numbers",
"aaSorting": [[ 0, "desc" ]],
"fnDrawCallback": function() {
  //bind the click handler script to the newly created elements held in the table
        $('.flagsmileysad').bind('click',flagsmileysadclick);
}
});

And that’s actually it. Simple, but effective, and a nice introduction to the handy fnDrawCallback feature of DataTables.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , , , . Bookmark the permalink.
  • http://carstereobluetooth.net/searching-for-the-right-car-stereo/ Searching For The Right Car Stereo » Car Stereo Bluetooth

    [...] jQuery: Bind an onClick Event to an Item in a DataTables Row [...]

  • http://blog.ericlamb.net Eric Lamb

    Seriously man, I was looking for just this solution. I have a data table that I want to use a jquery checkbox function with and I've been beating my head against the wall trying to figure out how to do this.

    Excellent example.

  • http://www.craiglotter.co.za Craig Lotter

    Glad I could help Eric. Seriously, datatables is just such a brilliant little plugin that the guys at jQuery really start bringing it into the core! :)

  • Taj360

    Hi, I can’t seem to get the id, any chance you post full code?
    Thanks
    Tom

  • http://www.craiglotter.co.za Craig Lotter

    Hi Tom. Which ID are you referring to?

  • Chh

    Great!
    It’s that what I need

  • http://www.craiglotter.co.za Craig Lotter

    Excellent :)

  • pwmusic

    You’re an absolute star!

    Thanks very much for posting.

  • Charles

    hi Craig,

  • Charles

    hi craig,
    I read about Fncallback..but I want to ask you about Datatables in show/hide details on a particular record. I did all the example that Allan has in this site. But no success..
    I want you to read this and tell me about the steps to do the code right. I have some question that I think can help me to do a light..
    1. sajaxSouce :”server_processing_details_col.php has the Echo $output
    Do I have to replace aaData[] into there?
    2. I use Datatables 1.7.5

    here is the discussion that
    http://datatables.net/forums/comments.php?DiscussionID=4251&page=1#Item_3

    mine is carlotor , there my code , in html -client- and in php
    february 28 /2011
    thanks in adavance if you decide to review this .
    Charles

  • Jess

    Can i ask how you managed to put the view link on each row when the data came from an external source?

    Thanks

    Jess

blog comments powered by Disqus