How to get the index of a row after its been sorted?

How to get the index of a row after its been sorted?

jstolpejstolpe Posts: 7Questions: 3Answers: 0

I need to loop over rows in a datatable and update a certain column in the row. I am using row().index() to get the row index and then calling cell( eq(rowindex),columnindex ) to update the correct column. The problem is the row().index() is not returning the correct index once the table gets sorted. It always returns the same index. I am guessing there is a way to get the row index based on the sorting of the table but have not been able to find any examples online. Here is my jsfiddle https://jsfiddle.net/xybjLugo/17/ you can see the salary in row 2 always gets updated no matter what the sort order is. Also, let me know if this is the best way to loop over a datatable and update a cell based on a rows id. Thanks!

This question has an accepted answers - jump to answer

Answers

  • jstolpejstolpe Posts: 7Questions: 3Answers: 0

    I think I finally found my answer, the third parameter of the "rows().every( function ( rowIdx, tableLoop, rowLoop )" function, "rowLoop", is the current index after the table has been sorted.

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited October 2015

    This is why i suggest using the rowId setting, which only works for ajax though.

  • jstolpejstolpe Posts: 7Questions: 3Answers: 0

    Thanks ill keep that in mind although I am not going to be using ajax for my current project. I updated the jsfiddle in case anyone in the future has the same problem. The correct row and cell now get updated regardless of how the table is sorted based off the row id.

    https://jsfiddle.net/xybjLugo/18/

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    Answer ✓

    Whoa, thats definitely not the right way to do it.

    You should be able to filter the rows to return only the row (or index) of the row that has the ID of whatever ID you want, something like

    target_row = exampleTable.rows().indexes().filter( function ( value, index ) {
      return exampleTable.row(index).data()[0] == 2; // Return only row with first column value of '2'
    } );
    
This discussion has been closed.