Issue with .on( 'click', 'tr', function ()

Issue with .on( 'click', 'tr', function ()

bbrindzabbrindza Posts: 316Questions: 73Answers: 1

I have an .on( 'click', 'tr', function () in my DataTable that is not working correctly. When I click one one row and then another , the class active is not remove on previous row.
I suspect it may be the createdRow: function( row, data, dataIndex ) { $(row).addClass( 'total-row' ); }, that I add previously before the function. Looking for a new set of eyes to see what I am missing.
Code below.

<div class='table-responsive tableFont'>
   <table class='table w-100  pt-2' id='timeLogTable_WeekEndingReportByManager'>
      <thead> 
         <tr>
           <th>Approved</th> 
          <th>Approved By</th> 
          <th>Name</th> 
          <th>Emp#</th> 
          <th>Dept</th> 
          <th>Date</th> 
          <th>Time In</th> 
          <th>Lunch Out</th> 
          <th>Lunch In</th> 
          <th>Time Out</th> 
          <th>Hours Worked</th>  
          <th>Lunch Time</th> 
          <th>Total Hours</th> 
          </tr>
       </thead> 
   </table>
</div>
timeLogTable_weekEndingReportByManager = $('#timeLogTable_WeekEndingReportByManager').DataTable( {

    displayLength:50,
    scrollY: '495px',
    scrollCollapse: true,
    paging: false,
    dom: 'Brtip',
    buttons: {
        buttons:[
                {
                  text: 'Approve Hours',
                 init: function(api, node, config) {
                        $(node).removeClass('dt-button buttons-print');
                        $(node).attr( 'id', 'approveHours' );
                  },

                 className: 'btn-primary',
                                     action: function ( e, dt, node, config ) {
                                   setApprovedHours()
                      },
                  enabled: false
               },
              {
                extend: 'print', 
                init: function(api, node, config) {
                    $(node).removeClass('dt-button buttons-print')
                 },
                className: 'btn-primary',
                exportOptions: {
                     columns: [ 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 17, 18, 20, 21]
                },

             title: 'Week Ending Report By Manager '+  $('#weekEndingReportByManager_weekEndingDate').val() + " for Manager " + weekEndingReportByManager_managerName + ' <br><div style="font-size:12px"> (printed by ' + employeeNameFirstLast + ')</div>' ,
             customizeData: includeSubtotals,

             customize: function(win) {
                $(win.document.body).find('h1').css('font-size', '15pt');   
                $(win.document.body)
                            .css( 'font-size', '8pt' );

                $(win.document.body).find( 'timeLogTable_WeekEndingReportByManager' )
                            .addClass( 'compact' )
                            .css( 'font-size', 'inherit' );

                    var last = null;
                    var current = null;
                    var bod = [];

                   var css = '@page { size: landscape; font-size: 8px}',
                        head = win.document.head || win.document.getElementsByTagName('head')[0],
                        style = win.document.createElement('style');

                    style.type = 'text/css';
                    style.media = 'print';

                    if (style.styleSheet)
                    {
                      style.styleSheet.cssText = css;
                    }
                    else
                    {
                      style.appendChild(win.document.createTextNode(css));
                    }

                    head.appendChild(style);
                    }
                 },
                {
                   text: 'Delete Time Log Record',
                   init: function(api, node, config) {
                            $(node).removeClass('dt-button buttons-print');
                            $(node).attr( 'id', 'removeTimeEntryCheck' );
                      },
                     className: 'btn-danger',
                     action: function ( e, dt, node, config ) { deleteTimeLogRecordModal('Week Ending By Manager Page')},
                      enabled: false
                   },
                     { text: 'Create Out of Office Entry',
                       init: function(api, node, config) {
                            $(node).removeClass('dt-button buttons-print');
                            $(node).attr( 'id', 'outOfOfficeButton' );
                      },  
                       className: 'btn-secondary',
                       action: function ( e, dt, node, config ) {createOutOfOffice() }
                      }
                  ],
            dom: {
                button: { className: 'btn btn-md'},
                buttonLiner: { tag: null }
               }
         },         
    language: {  sSearch: 'Table Search: '},
    processing: true,
    serverSide: true,
    ajax: {
            url: "ssp_WeekEndingReportByManager.php",
            dataType: 'json',
            data: { weekEndingDate: $('#weekEndingReportByManager_weekEndingDate').val(),
                    managerNumber: weekEndingReportByManager_managerNumber,
                    employeeNumber: sessionEmployeeNumber 
                   },
    },
    columns: [    
              { data: 'hours_approved'},
              { data: 'hours_approved_by'},
                  { data: 'employee_full_name'},
                  { data: 'employee_number'}, 
                  { data: 'employee_department_code'},
              { data: 'time_log_date'},
              { data: 'time_in' },
              { data: 'lunch_out'},
              { data: 'lunch_in''}'
              { data: 'time_out''}'
              { data: 'hours_worked''},
              { data: 'total_lunch' },
              { data: 'total_hours',},
              { data: 'total_hours_time_format'}, 
            ] , 
       columnDefs: [
                {
                  targets: 1,
                  render: function(data, type, row, meta){
                      data = '<input type="checkbox" class="select-checkbox">'

                      if(row['hours_approved'] == 'Y'){
                         data = '<span class="checkMark">&#10003</span>';
                      }

                      return data;
                   },
                createdCell:  function (td, cellData, rowData, row, col){
                    if(rowData['hours_approved'] == 'Y'){
                        this.api().cell(td).checkboxes.disable();
                     }
                   },            
                },
             ],
    select: {style: 'multi' },              

    order: [[3, 'asc'],[4, 'asc'],[23, 'asc'],[22, 'asc']],

    rowGroup: {
              dataSrc: [ 'week_ending_date_row_group',  'employee_information_row_group' ],
    },

    createdRow: function( row, data, dataIndex ) {
              $(row).addClass( 'total-row' );
     },

     drawCallback: addSubtotals, 

  });//END .dataTable

    $('#timeLogTable_WeekEndingReportByManager tbody').on( 'click', 'tr', function () {
        if ( $(this).hasClass('active') ) {
              $(this).removeClass('active');   alert('Remove active')
       }
        else {
              timeLogTable_weekEndingReportByManager.$('tr.active').removeClass('active');
              $(this).addClass('active');  alert('Add active')
        }
    } ); 

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,482Questions: 1Answers: 10,467 Site admin

    Seems to work here: https://live.datatables.net/yegegomo/1/edit .

    Can you link to a test case showing the issue please.

    Allan

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Stand by Allan, Need to build it out. I will post the test case when I completed it.

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Here is the test case https://live.datatables.net/pahocazi/1/edit

    However when I add datatables.buttons lib I get this error "Script error. (line 0)"

    Maybe you can see what I am doing wrong.

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

    However when I add datatables.buttons lib I get this error "Script error. (line 0)"

    The browser's console (don't use the JS Bin console) shows this error:

    Uncaught Cannot extend unknown button type: print

    I removed the buttons config as its not needed for the issue you are trying to solve. For demonstration purposes I commented out the select option and added the CSS Allan used in his example:

    .active {
      color: blue;
    }
    

    The click event seems to be working and toggling the active class:
    https://live.datatables.net/pahocazi/2/edit

    Please provide the steps to see the issue you aer having. What are you trying to do with the active class?

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Hi Kevin ,

    I only want to select only one row at a time . The problem with my application on our server is not removing the "active" class from the row that was previously click, which will cause a issue when using the "delete" button in my table. It will keep the "active" class set on any row clicked.

    However I noticed that you have commented out the select: {style: 'multi' },

    I commented that line out in my script and know I cannot select any rows.

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

    However I noticed that you have commented out the select: {style: 'multi' },

    As I said, I commented this out to show the CSS styling is applied. It is simply for demonstration purposes. Otherwise you wouldn't see the blue text being applied with the selected row.

    The problem with my application on our server is not removing the "active" class from the row that was previously click,

    @allan 's example uses your code snippet and it works. It works across pages, meaning click a row on page 1 go to 2 click another row and the active class is removed from page 1. The timeLogTable_weekEndingReportByManager.$('tr.active') will find all rows with the active class. There must be something else on your page affecting the active class. Can you provide a test case showing the issue?

    Kevin

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948
        $('#timeLogTable_WeekEndingReportByManager tbody').on( 'click', 'tr', function () {
            if ( $(this).hasClass('active') ) {
                  $(this).removeClass('active');   alert('Remove active')
           }
            else {
                  timeLogTable_weekEndingReportByManager.$('tr.active').removeClass('active');
                  $(this).addClass('active');  alert('Add active')
            }
        } );
    

    One thing you can try to verify this code is to place a browser's breakpoint on line 7. Click a row then click another row. At the breakpoint you should be able to verify that the active class was removed from all rows. If this happens but you still have issues then you know the problem is elsewhere.

    Kevin

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

    I updated @allan 's example with Select. You can still see that the active class is removed.
    https://live.datatables.net/yegegomo/3/edit

    If it weren't removed the previously clicked row text would be blue.

    Kevin

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948
    Answer ✓

    Even easier than using a browser's breakpoint is to temporarily add the CSS Allan tested with. You should never see teh blue text if the active class is prperly removed.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    I found the culprit. I was missing the js select: true, Thank you all for you help

Sign In or Register to comment.