How to set cell value in DataTable on button click

user3295211 picture user3295211 · Mar 28, 2016 · Viewed 11.1k times · Source

I'm trying to modify a cell value using DataTable (the new version) when an outside button is clicked. I have the following for now:

$(document).on('click', '.dropdown-menu li a', function () {
    if ($(this).text() == "development") {
        var cell = table.row( 6 ).data()[4]     
        cell.data( "development" ).draw();
    }
});

This doesn't work since I think the table row and data retrieval method doesn't return an object with .data() attribute that allows me to set data cell value. I'm getting the following error: cell.data is not a function. (In 'cell.data( "development" )', 'cell.data' is undefined)However, I'm not sure how to access a table cell value the .data() way without having a click even in the table. My button is placed outside the table somewhere else.

Any idea how to make this work?

Answer

CMedina picture CMedina · Mar 28, 2016

Since DataTables 1.10+ might not support fnGetNodes() as mentioned on the API landing page itself, instead now you can use rows().nodes().

Example: http://jsfiddle.net/cmedina/7kfmyw6x/28/

var table = $('#example').DataTable({sorting : false});
var row = table.row(0).node();   

$('#test').on( 'click', function () {
    var text = "development";
    if (text == "development") {
       table.cell(row, 0).data('Development').draw();
    }
});

If you work with DataTables < 1.10 then you can use fnUpdate

Example: http://jsfiddle.net/cmedina/7kfmyw6x/29/

var oTable = $('#example').dataTable({sorting:false});

$('#test').on( 'click', function () {
   var text = "development";
   if (text == "development") {
     oTable.fnUpdate('Development', 0, 0 ); // Single cell
   }
})