Color selected row in datatable

Color selected row in datatable

Stepan123Stepan123 Posts: 10Questions: 3Answers: 0

I want to add selected class to datatable's row when row is selected by user to be able later to color the row. Unfortunetly i have error i dont know how to solve. My datatable id is called dataTb

 $(document).ready(function () {
    $("#dataTb tbody").on("click", "tr", function () {
      var selected = $(this).hasClass("selected");
  
      // $('#dataTb tbody tr').removeClass('selected');
      if (selected) {
        $(this).removeClass("selected");
      } else {
        table.$("tr.selected").removeClass("selected");
        $(this).addClass("selected");
      }
    });
  });

and in my css i have this:

#dataTb .selected {
    color: white;
    background-color: #316435;
}

nevertheless when i navigate to my page's table in console it throwns me this error:

Uncaught ReferenceError: dataTable is not defined
    at HTMLTableRowElement.<anonymous> (scripts.js:167:9)
    at HTMLTableSectionElement.dispatch (jquery-3.6.0.min.js:2:43064)
    at v.handle (jquery-3.6.0.min.js:2:41048)

this is thrown on this line:

table.$("tr.selected").removeClass("selected");

Answers

  • rf1234rf1234 Posts: 3,000Questions: 87Answers: 421

    Could you post the error message please

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    You are using a variable "table" which does not exist. Either declare it globally or initialise it inside your function.

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin

    I don't actually see where dataTable is being used and where it would be throwing an error either.

    I reckon we'll need a link to a page showing the issue to be able to help resolve this.

    Allan

Sign In or Register to comment.