Automatically select row if cell has class

Automatically select row if cell has class

karibusanakaribusana Posts: 11Questions: 5Answers: 0

Hi
I'm using datatables with the select plugin, I need to automatically select a row if a cell in that row has a specific class in particular my class is called .favourite
My data come from server side and I use ajax to load them into datatable, this is how the html looks like https://codepen.io/karibusana/pen/jOaZbNB so you can see the class .favourite

I've tried with rowCallback

      rowCallback: function(row, data, index) {

              var cellValue = data["descrizione"];

              if($(cellValue).find('.favourite')){

               dataTable.row().select();

              }
            }

But all it does is select the first row and not the one with .favourite class. Can anybody help me please? many thanks

Answers

  • allanallan Posts: 63,489Questions: 1Answers: 10,470 Site admin

    You aren't providing a selector to the row() method, so yes, it will just be picking the first row in the table, since no selector equals all rows (which with the singular row() method gets truncated to just one row).

    What I would actually suggest in this case is:

    if ($(row).find('.favourite')) {
      dataTable.row( row ).select();
    }
    

    Note how the row parameter from rowCallback is being passed into the row() method to select that row. The condition also makes use of the existing row rather than creating new DOM elements from the string value.

    Allan

  • karibusanakaribusana Posts: 11Questions: 5Answers: 0

    Hi @allan many thanks for your help. I've tried your suggestion but I now get all rows selected :( any other suggestion? many thanks

  • kthorngrenkthorngren Posts: 21,318Questions: 26Answers: 4,948

    I think you need to use $(row).find('.favourite').length. Like this:
    http://live.datatables.net/vejupeye/1/edit

    Kevin

  • karibusanakaribusana Posts: 11Questions: 5Answers: 0

    Hi @kthorngren tanks for your precious help it worked.
    Many thanks to @allan as well.

Sign In or Register to comment.