Changing data-order after initialization

Changing data-order after initialization

SpartachSpartach Posts: 2Questions: 1Answers: 0

I have a column with checkboxes, and I want to be able to order by this column; i.e., when I click on the header of this column, I want to see all rows with checked boxes on top.
I tried to use the method from https://datatables.net/forums/discussion/20950/changing-data-order-after-initialization , so I use the data-order attribute of <td> tag; in the beginning all attrs are equal to 1, and after checking the box the attr becomes 0.
I do both row().invalidate() and cell().invalidate(), but nothing helps - this row doesn't sort according to data-order!
Here is a small example: http://chgkstat.org/datatables_example
Check the second checkbox, then press button. You'll see that second <td> has data-order=0 and other cells in this column have data-order=1. But first column still doesn't sort when you click its header!
Can you please see how to fix this?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947
    edited January 2018 Answer ✓

    Two things I think you need to change.

    First change this:
    cur_cell.data('order', cur_chkbox.prop('checked') ? 0 : 1);

    to this:
    cur_cell.attr('data-order', cur_chkbox.prop('checked') ? 0 : 1);

    This will set the attribute data-order to 0 or 1.

    Then change your sort order to this:
    "order": [[ 0, "asc" ]],
    or
    "order": [[ 0, "asc" ], [ 1, "asc" ]],

    Currently you are sorting by column 1 not column 0 so you won't see any changes to the order based on the checkbox (data-order) value.

    Then either row().invalidate() and cell().invalidate() should work.

    Kevin

  • SpartachSpartach Posts: 2Questions: 1Answers: 0

    kthorngren, first method worked, thank you!!

    I still don't understand the difference between cur_cell.data('order') and cur_cell.attr('data-order') but it worked.

    Changing the sort order seems to be irrelevant here: it determines just the initial sorting of rows, and I don't need to change it now.

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    My understanding from the jQuery .data() docs is that jQuery stores the values internally and does not change the actual attribute:

    The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

    If you use the browser's inspect tool you can see that the attribute is not changed when using jQueries .data() method.

    Kevin

This discussion has been closed.