Change cell data after sorting table

Change cell data after sorting table

VoliverioVoliverio Posts: 3Questions: 1Answers: 0

Hi, I have the following code to update a table cell data:

                //Gets the table reference
                var dataTableRef = $('#tabelaConsulta').DataTable();

                //Finds the row that needs to be updated
                var rowToUpdate = -1;
                var data = dataTableRef.rows().data();
                data.each(function (value, index) {
                    if (value[12] == id) {
                        rowToUpdate = index;
                    }
                });

                //Updates the row cell
                dataTableRef.cell(rowToUpdate, 4).data(quantidade);

When the table is not sorted it works just fine, but if I sort the table it doesn't change the row it should, it changes the row the data was before being changed, i.e., before sorting the table the row I need to change was 15, when I sort the table the row 15 goes to 10th position, if I execute the code above it changes the data on row 15 not row 10.

Thank you.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,250Questions: 26Answers: 4,761

    Its unclear to me what you are trying to do. Please build a simple test case with an example of your data so we can take a look at the running code.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • VoliverioVoliverio Posts: 3Questions: 1Answers: 0
    edited September 2020

    Hi,

    Here it is:
    http://live.datatables.net/yafuwijo/1/

    Click on the "Change Data" button without sorting the table, it will change the name of the 9th row, refresh the page, sort the table by age and click on it again, it will change the name of the 6th row, but js the code is:

    function ChangeData()
    {
      //Gets the table reference
    var dataTableRef = $('#example').DataTable();
     
    //Updates the row cell
    dataTableRef.cell(3, 0).data('testing');
    }
    
  • kthorngrenkthorngren Posts: 20,250Questions: 26Answers: 4,761
    Answer ✓

    The cel() uses the row-selector options for selecting the row. You are supplying an integer which is the row index. The row index is the order of the original data. The Cedric Kelly row is the 4th row in the original data (row indexes count from 0). No matter how you sort the table dataTableRef.cell(3, 0).data('testing'); is always going to change Cedric Kelly.

    I think I understand what you are trying to do now. I think what you really want to use is the row-selector() as a function with the rows() API to find the row you want. Then use that row with api cell() to update the cell. For example:
    http://live.datatables.net/kutikuwo/1/edit

    Kevin

  • VoliverioVoliverio Posts: 3Questions: 1Answers: 0

    Hi Kevin,

    It worked perfectly!

    Thank you very much!

This discussion has been closed.