Search code examples
javascriptjqueryfunctionevent-listenereventhandler

eventHandler trigger multiple times when using .on() only


function changeStatus() { 
$('#dataTable tbody').on('change', '.orderStatus', function () {..code} 
}

function showOrdersInModal() { 
    $('#dataTable tbody').on('click', '.fa-eye-btn', function (e) {...code} 
    }
        
function addUrl() { 
$('#dataTable tbody').on('click', '.addUrl', function () {..code} 
}
    
function showOrders() {
  $.ajax({
    type: 'method',
    url: 'url',
    data: { data },
    success: function (response) {
      $('#dataTable').DataTable().clear().destroy();

      let data = JSON.parse('[' + response.replace(/}{/g, '},{') + ']');
      
      $('#dataTable').DataTable( {
        autoWidth: false,
        pageLength: 25,
        lengthMenu: [[25, 50, 100, 500, -1], [25, 50, 100, 500, 'All']],
        data: data,
        columns: [
            { data: 'receipt' },
            { data: 'first_last_name' },
            { data: 'contact_no' },
            { data: 'address' },
            { data: 'email' },
            { data: 'url' },
            { data: 'status' },
        ],
      });

          showOrdersInModal();
          changeStatus();
          addUrl();
    },
  });
}

showOrders();

When I use .off() before .on(), the only last function will execute which is addUrl(); but when I remove the .off() it will trigger the event depending on how many times I click any of each button or element.

Is there a way that I can make the eventHandler trigger once even if I clicked any of the buttons multiple times?

or is there a way to execute all three functions not just the addUrl(); function at the end?


Solution

  • I found the answer and when using the dataTables I cannot access the DOM after the next page so I use drawCallback which like this:

    $('#dataTable').dataTable({
        drawCallback: function () {
          showOrdersInModal();
          changeStatus();
          addUrl();
        },
        retrieve: true,
        deferRender: true,
        data: data,
        columns: [
          { data: 'data' },
        ],
      });
    

    then I just use this.

    $('.className').off().on('click', function () {..code}