How to add "selected" class to the first row displayed when the page changes?

How to add "selected" class to the first row displayed when the page changes?

Leo BrunoLeo Bruno Posts: 19Questions: 3Answers: 0

Hi:

I´m looking for a way to add the "selected" class (i´m not using the select extension), after the pagination changes.

I´have seen some instructions to use DrawCallBack, but it is fired BEFORE the page changes, so I´m lost.

How can I achieve this?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    edited November 2022
    table.on('draw', function () {
      var tr = table.row(':eq(0)').node();
    
      tr.classList.add('selected');
    });
    

    Allan

  • Leo BrunoLeo Bruno Posts: 19Questions: 3Answers: 0

    Hi Allan....

    Thank you for answering.

    It partially worked.

    The dataset has two pages.

    When I go to page 2, the first row is not selected.

    Then when I go back to page 1, the first row get´s selected.

  • Leo BrunoLeo Bruno Posts: 19Questions: 3Answers: 0

    Well, it din´t work at all.

            table.DataTable().on('draw', function () {
              var tr = table.DataTable().row(':eq(0)').node()
              console.log(tr)
              tr.classList.add('selected')
              console.log(tr)
            })   
    
    

    Inspecting the console.lod data, I could see that is the row at page 1 that is being selected, when page 2 is drawn.

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    Answer ✓

    I changed the jQuery selector to 'tr:first-child'which works and 'tbody tr:eq(0)' which also works. See this example:
    http://live.datatables.net/nuhibola/1/edit

    I'm not sure how Datatables processes the :eq(0) selector versus 'tbody tr:eq(0)' but there is something different as it seems to use the Datatables cache instead of what is in the DOM.

    Kevin

  • Leo BrunoLeo Bruno Posts: 19Questions: 3Answers: 0

    Thank you Kevin and Allan.

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    Ah yes sorry. I forget to add {page: 'current'} as the second parameter to my row() selector. Doh.

    Allan

Sign In or Register to comment.