Add checkbox to each row in datatable for selecting rows

Add checkbox to each row in datatable for selecting rows

madaan18madaan18 Posts: 4Questions: 0Answers: 0
edited September 2012 in TableTools
Hi folks,

I was just wondering if i can have an extra column in my datatable which will contain checkboxes to select/deslect rows. I googled and found following 2 links, they are quite helpful but not exactly what i want.

http://datatables.net/release-datatables/examples/api/select_row.html
http://datatables.net/release-datatables/examples/api/form.html

Is there not any variable or api directly to have this feature. I want to have select all/deselect all option also in the header of table. Please guys tell me what is the best way to do so ?

Thanks $ Regards
Tarun Madaan

Replies

  • allanallan Posts: 63,680Questions: 1Answers: 10,498 Site admin
    Currently no - this is not a built in option. TableTools has whole row selection: http://datatables.net/release-datatables/extras/TableTools/select_multi.html but not checkbox selection.

    Allan
  • madaan18madaan18 Posts: 4Questions: 0Answers: 0
    Thanks Allan for replying.

    But in second link ( http://datatables.net/release-datatables/examples/api/form.html ) there are checkboxes and submit button which will give the selected rows. Can you please share that code? how to do so ?

    Thanks $ Regards
    Tarun Madaan
  • girishmrgirishmr Posts: 137Questions: 0Answers: 0
    edited September 2012
    with 1.9.3 using mRender is the way to go. Still you can use fnRender.
    Here is a bit of sample code for you. Might help

    [code]
    {
    // Targets column 8 (count from 0)
    "aTargets":[8],
    // Some styling
    "fnCreatedCell": function(nTd, sData, oData, iRow, iCol)
    {
    $(nTd).css('text-align', 'center');
    },
    // Extra column where you want your link/add/delete/edit buttons or in your case check boxes
    "mData": null,
    "mRender": function( data, type, full) {
    return '';
    }
    },
    [/code]

    If you intended to have one action per row, you can use the following code which gives the row id of clickacble row

    [code]

    // Gets you the row Id
    var rowIndex = oTable.fnGetPosition($(this).closest('tr')[0]);

    [/code]

    In case you have multiple actions per row, use the following code

    [code]
    // Only column 8 is clickable
    $("#example td:nth-child(8)").live("click", function () {});
    [/code]

    Also do not forget to use a class (not an ID since this should be unique) for checkboxes on each row and use .each to loop thru'

    Hope this helps
  • allanallan Posts: 63,680Questions: 1Answers: 10,498 Site admin
    @madaan18 - The code is there in that example...

    As girishmr says, if you want to create input elements on-the-fly, then mRender is the way to do.

    Allan
  • davidhcdmdavidhcdm Posts: 7Questions: 1Answers: 0
    Hello allen, this is my first post. I'm adding on to this thread instead of creating my own because I am trying to add a checkbox to my dataTable and I want to be a good netizan and not re-create a topic. Namely, using mRender to add a checkbox to my data rows.

    I have managed to create a working example of using dataTables with a .NET .aspx Webmethod that returns POST JSON Data from a form submission and populates a dynamic table. On the aspx page I have the table laid out as in your basic examples, including a for the "Select" column.

    Here is my code as it is currently, including placement code similar to that listed above. It is not rendering a checkbox currently, but is rendering my row data, with all data rows shifted one column to the left. I want to inject the checkbox into column 0 and it should have a value = to "TaskID". First I want to get past rendering the checkbox, then I will deal with getting the checkbox value back on a button click later...

    Here is my code:
    [code]
    $(document).ready(function () {
    // Can't get this to work against data rows;
    // discarding for now...
    // $('#example tr').click(function () {
    // $(this).toggleClass('row_selected');
    // });
    // var oTable = $('#example').dataTable();
    $('input[id*=ParamButton]').click(function () {
    var paramSearchURL = "MyPage.aspx/SearchViaParams";
    var sUrl = "MyPage.aspx/SearchViaParams";
    // disablePage(); // disabling for now while debugging
    // showProgress(); // disabling for now while debugging
    //Search Parameters to pass to web method...
    var parameterCriteria1Field = $('select[id*="SearchParamCriteria1"]');
    var parameterValue1Field = $('input[id*="SearchParamValue1"]');
    var pageData = {
    ParameterCriteria1: parameterCriteria1Field.val().toString(),
    ParameterValue1: parameterValue1Field.val().toString(),
    };
    $('#example').dataTable({
    "bProcessing": true,
    "bDestroy": true, //this flag must be implemented -->
    // to destroy and rebuild dataTable
    //"bServerSide": true, //NOT USED IN CLICK -->
    // WEBMETHOD JSON SCENARIO
    "sAjaxSource": sUrl
    "sAjaxDataProp": "", //EMPTY STRING is needed -->
    // to handle .NET json "d.Tablename notation -->
    // returned from WebMethod
    "sServerMethod": "POST",
    "fnServerData": function (sUrl, aoData, fnCallback, oSettings) {
    oSettings.jqXHR = $.ajax({
    "type": "POST",
    "url": sUrl,
    "dataType": "json", //NOT pjson!
    "cache": false,
    "contentType": "application/json; charset=utf-8",
    // The following works with .NET Webmethods
    "data": "{'items': '" + JSON.stringify(pageData) + "'}",
    "success": function (json) {
    fnCallback(json.d.Table);
    },
    "error": function (msg) {
    alert(msg);
    }
    });
    },
    // Code below, above aoColumns, is non-working code -->
    // trying to insert checkbox in first ordinal datarow position
    "aTargets": [0],
    // Some styling
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
    $(nTd).css('text-align', 'center');
    },
    // Extra column where you want your check boxes -->
    // (I don't understand this...)
    "mData": null,
    "mRender": function( data, type, full) {
    // I think this is correct code to add checkbox? -->
    // Value should =TaskID
    return '';
    },
    "aoColumns": [
    { "mDataProp": "TaskID" },
    // more columns removed for brevity....
    { "mDataProp": "MessageData" }
    ]
    }); //I removed a lot of JS below this, hope closing brackets are correct... ;)
    });
    });
    [/code]

    Thanks in advance for your help, and I hope the code above helps folks working in .NET. I tried to comment the code so the .NET folks will catch the subtle tricks to getting this scenario to work. I'd be happy to post a detailed how-to after this checkbox works if you would like me to...
  • davidhcdmdavidhcdm Posts: 7Questions: 1Answers: 0
    edited January 2013
    A few lines of code above were tweeked by your server. Line 26 specifically. Line 26 should read:
    "sAjaxSource": sUrl,

    Line 27, 28 and 29 should read (including comments):
    "sAjaxDataProp": "", //EMPTY STRING is needed -->
    // to handle .NET json "d.Tablename" notation -->
    // returned from WebMethod

    Just FYI for those who may visit this later.
  • davidhcdmdavidhcdm Posts: 7Questions: 1Answers: 0
    I got this to work!

    After much Googling, I ran across a thread where allan pointed out that as of 1.9.4 mDataProp and fnRender had been depricated, and instead you should use mData and mRender. So I made that switch, but more importantly, I was pointed to http://datatables.net/ref#mRender that had a nice bit of demo code at the bottom that I pasted into my code to get that first column to render. From there I played with it some more and with the following code I now get a checkbox, centered in every row at column 0 with a value I can use in later click events:

    [code]
    ...
    "aoColumns": [
    { "sClass": "center",
    "mData": "TaskID",
    "mRender": function (data, type, full) {
    return '';
    }
    },
    {"mData": "TaskID" },
    ...
    [/code]

    :)
This discussion has been closed.