3

I have created a function to swap rows in a table, but it doesn't seem to be working correctly. The data for the rows doesn't seem to be matching up with the data that is in the array. Can anyone help point out the bug in my code, or how I may be misusing some of the DataTable functions?

function swapDataTableRows(selector, row1Index, row2Index)
{
    var datatable = selector.DataTable();
    var rows = datatable.rows().data();
    var row1Data = datatable.row(row1Index).data();
    var row2Data = datatable.row(row2Index).data();

    datatable.row(row1Index).data(row2Data);
    datatable.row(row2Index).data(row1Data);
}

swapDataTableRows(table, 2, 3) - It will swap rows 1 and 2. If I add 1 to the indexes then it goes out of bounds.

3 Answers 3

3

I'm not sure to have understood your problem...

I try to create a simple demo to understand:

http://jsfiddle.net/q0zb1rkc/

... in your functions you never draw the table with new (edited) data:

I change this 2 rows of your script:

datatable.row(row1Index).data(row2Data);
datatable.row(row2Index).data(row1Data);

and i add .draw():

datatable.row(row1Index).data(row2Data);
datatable.row(row2Index).data(row1Data);

width .draw() also DOM change and the ROW1 and ROW2 exchange.

Sign up to request clarification or add additional context in comments.

3 Comments

To make it more clear row(index) is returning an unexpected row.
can you share the log of the row2Data and row1Data ?
I found the issue. The index I was passing in was based on what was being displayed. It was not the row index from the api. Once I used the api it fixed the issue. The function is correct.
1

From Frogmouth's answer,

`http://jsfiddle.net/bobxdr7c/`

I added some changes.

Since the ordering option is set true as default when instantiating Datatable, whenever you try to swap their data and redraw it, it looks not what you would expect.

To fix this problem,

  1. check your 'ordering' option set 'false'.
  2. don't call draw() function twice. it's enough to call once at the last statement.

P.S. hm, it seems I cannot make a jsfiddle link in the post directly. :(

Comments

0

If this is not the first switch of rows, you are most likely using the wrong row index. The index that is shown in the DOM is not necessarily the index the row has in the api. Have you tried addressing the rows with specific selectors like their id? e.g.: datatable.row("#row1id")

Also for the changes to be updated in the DOM you will need to call datatable.draw() after all the data switching is done.

Comments

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.