Boap
Boap

Reputation: 25

DataTables js columnDefs render function using variable

I'm trying to pass a variable to use for the columnDefs render function property of the DataTable, but I always get an error when doing so.

If I put the same function contained in that variable directly as the render property, it works with no issues and I get the desired functionality.

The error I get when trying to use the variable: DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter 'someColumn' for row 0, column 6.

 function WriteReportTable(data, dataTableSettings) {
    var renderFunction = function (data) {
        if (data == 'i') {
            return 'In';
        }
        return data;
    };
    var tableSetUp = [$('#tableReportDataHeader'), $('#tableReportDataFooter')];
    for (var i = 0; i < tableSetUp.length; i++) {
        var th = $('<tr/>').appendTo(tableSetUp[i]);
        for (var j = 0; j < dataTableSettings["columnDisplayNames"].length; j++) {
            th.append('<th>' + dataTableSettings["columnDisplayNames"][j] + '</th>');
        }
    }

    //get column names from json data
    var columns = [];
    columnNames = Object.keys(data[0]);
    for (var i in columnNames) {
        columns.push({ data: columnNames[i], title: dataTableSettings["columnDisplayNames"][i] });
    }

    RDataTable = $('.rDataTable').DataTable({
        pageLength: 10,
        data: data,
        sDom: '<"#selectDtBtn.selectDtBtn"><"#showInfoBtn.optionBtn">T<"html5buttons"B>fgitlp',
        responsive: true,
        autoWidth: false,
        bAction: false,
        columns: columns,
        order: dataTableSettings["order"],
        columnDefs: [{
            targets: dataTableSettings["columnDefsTargets"],
            render: function (data, type, row) {
                renderFunction(data);
            }
        }]
    });
}

So if the rederFunction(data) in columnDefs is replaced with the function itself:

if (data == 'i') {
    return 'In';
}
return data;

Then it works as expected. Not sure how to get it work with the variable instead. Thanks!

Upvotes: 0

Views: 2212

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

It's not working because it's not returning anything. You need to return what the function returns.

render: function (data, type, row) {
    return renderFunction(data);
}

Or instead of having a function that does nothing but call another function...

render: renderFunction

Upvotes: 0

Related Questions