Sorting breaks after programmatically changing data-sort value

Sorting breaks after programmatically changing data-sort value

cheaperjcheaperj Posts: 2Questions: 1Answers: 0

I have a table with a column that is used to show if a person liked a certain item. After I create the row using fnAddData() I add the data-sort attribute to the <td>:

// Instantiate the data table.
// 
var oTable = domainsTable.dataTable({
    'aaSorting' : [],
    'aoColumns' : [
        {},
        {},
        {},
        {
            'sType' : 'numeric'
        }
    ],
    'bDestroy'  : true,
    'bPaginate' : false,
    iDisplayLength: -1,
    'oLanguage' : { "sZeroRecords" : 'No results' }
});
// ...queried the database via $.ajax();
//..take the response data and looop through the results
for( var i = 0; i < results.data.length; i++ )
{
    // I add the row to the table.
    //
    var a = oTable.fnAddData([
     'Some Value',
     'Some Value',
     'Some Value',
     '<span class="unfavored-item"><i class="fa fa-heart"></i></span>'
     ]);

    // Here i add the data-sort attribute with the value of 0 which the 0 represents
    // the item not being like by the user.
    // 
    var oSettings = oTable.fnSettings();
    var nTr = oSettings.aoData[ a[0] ].nTr;
    $('td:nth-child(4)', nTr).attr('data-sort', results.data[i].favorite);
}

At this point the table properly sorts the column based on the data-sort attribute value. The problem I'm having is that when I update the data-sort value (from 0 to 1 as an example via DOM modification) the datatable doesn't honor the change thus the sorting is not sorting correctly.

Here's the snippet where I"m updating the DOM:

var oSettings = oTable.fnSettings();
var getPosition = oTable.fnGetPosition($(this).closest('tr').get(0));
$('td:nth-child(4)', getPosition).attr('data-sort', 1);

What do I need to do for the datatable to honor the change so that sorting operates correctly?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,431Questions: 1Answers: 10,048 Site admin
    Answer ✓

    Use row().invalidate() to invalidate the data that DataTables has cached for the filter / sort.

    Allan

  • cheaperjcheaperj Posts: 2Questions: 1Answers: 0

    Allan,

    Thank you for your help. The following did the trick:

    oTable.api().rows().invalidate('dom').draw();
    
This discussion has been closed.