8

we have a table in our page, with a few rows and a custom toggle button at the end. the table is loaded via html in the page, not via json.

now, the togglebutton at the end posts to a service and sets the follow state of that record in the database.

however, it should also make an update to another cell in that row. however i'm sure i should not do this via jquery manually but via datatables?

$('#tblFollow').dataTable({
    sDom: "t",
    aoColumns: [
      null,
      null,
      null,
      { bSortable: false }
    ]
});

$('#tblFollow').on('click', 'a.follow', function(e){
    $(this).toggleClass('active');

    // updating column 'following' here... 
    // but this only changes visually, and not the inner datatables data used for sorting
    var followingCell = $(this).parents('td').prev();
    var txt = followingCell.text() == "1" ? "0" : "1";
    followingCell.text(txt);

    return false;
});

manual example: now i have an example, where i change the fields manually, but that's only visual, the datatable still uses its inner data for sorting. So i'm looking for a way to do it better

1 Answer 1

15
+250

Here is a possible solution:

In addition to your code you should update the datatables data as following

var rowIndex = table.fnGetPosition( $(this).closest('tr')[0] );
var aData = table.fnGetData( rowIndex  );
aData[2] = txt; //third column

Here the jsfiddle

And even better solution would be to use fnUpdate to update the data and display in the same time

Here the jsfiddle

// update column following here... 
var followingCell = $(this).parents('td').prev();
var txt = followingCell.text() == "1" ? "0" : "1";

var rowIndex = table.fnGetPosition( $(this).closest('tr')[0] );
table.fnUpdate( txt, rowIndex , 2);

Also instead of us

var followingCell = $(this).parents('td').prev();
var txt = followingCell.text() == "1" ? "0" : "1";

use

var aData = table.fnGetData( rowIndex  );
aData[2] //use it to check if the value is 0 or 1
Sign up to request clarification or add additional context in comments.

2 Comments

that works like a charm. sorry the optimization you did at the end, to check the value on aData instead of on the text of the cell, was not necessary but interesting. I only used it in my example jsFiddle... my own code already knew the text from data properties on the button. but i didn't want to complicate the jsFiddle too mutch. still interesting. thanks.
Pay attention, this solution seems to work only with legacy dataTables. In dataTables 1.10.7 I use table.cell(targetCellSelector).data("new text").draw();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.