Search code examples
datatablesrowid

How to generate jQuery DataTables rowId client side?


The jQuery DataTables reference shows an example of setting the rowId option to a column from the data source (server side). This setting is used for the "select" extension and retaining row selection on Ajax reload.

Is there any way to generate the row identifier value 1) client side, or 2) as a combination of multiple columns from the data source?

Example data source:

{
    "data": [
    {
        "aid": 5421,
        "bid": 4502,
        "name": "John Smith"
    }
}

Code:

$("#datatable").DataTable({
    select: true,
    //rowId: "aid" each row ID is the value of the "aid" column
    //       e.g., <tr id="5421">

    //rowId: 0 each row ID is the value of the 0-indexed column
    //       e.g., <tr id="5421"> (same as above)

    rowId: [0, 1] // How? row ID combined value of 2+ columns
                  // e.g. <tr id="5421-4502">

    rowId: "random" // How? random generated client-side ID
                    // e.g., <tr id="id34e04">
});

Solution

  • Apparently there's no way to do this directly. As a workaround, you could use the ajax.dataSrc option and/or the rowId option:

    // Example using dataSrc option to manipulate data:
    $("#example").dataTable({
        ajax: {
            url: "data.json",
            dataSrc: function (json) {
                for (var i = 0, ien = json.data.length; i < ien; i++) {
                    json.data[i][0] = '<a href="' + json.data[i][0] + '">View Message</a>';
                }
            }
        }
    });