4

I'm using jQuery DataTables ( http://www.datatables.net ) to generate a table. I want to insert in certain cells(from a column) a jquery generated html element witch has some events attached to it. (onClick for example).

I was thinking about mRender but I found that I need to return a string instead of an object.

here is the code:

table.dataTable({
    "aoColumns": [{
        "mRender":function() {
            var element=$("<div></div>").on("click",function(){
                alert("do something");
            });
            return element;
        }
    },
    {"sWidth": "350px"}]
});

The code is not working because what I see rendered is

[Object]

I can get the html code of the element using jQuery.html() but then I will loose the events attached to the element.

Is there any solution? Is this a design flaw in DataTables or am I missing something?

Doua Beri
  • 10,612
  • 18
  • 89
  • 138
  • dataTables uses innerHTML internally to render the markup passed in mRender, so passing a jQuery object is as far as I know not possible. – adeneo Sep 19 '13 at 17:47
  • @adeneo thanks , I was afraid someone might say this. So the only solution is to re-write the rendering method to accept jquery object and not just string. Do you know what's the name of that method? – Doua Beri Sep 19 '13 at 17:52

1 Answers1

5

You can insert placeholder elements via mRender or sDefaultContent and add the actual content and events during the fnRowCallback events. Something like this:

table.dataTable({
    "aoColumns": [{
        "sDefaultContent": '<div class="stuff"></div>'
        "sWidth": "350px"
    }],
    "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        var element = $(nRow).find("div.stuff");
        // do stuff
        element.on("click",function() {
            alert("do something on row: " + iDisplayIndex);
        });
    }
});
Gigo
  • 3,188
  • 3
  • 29
  • 40