0

i'm using datatables from : https://www.datatables.net/

and also i'm using Bootstrap Toggle from : http://www.bootstraptoggle.com/

Here is my code :

<table class="table table-striped table-hover" id="table-list-tour">
  <thead>
    <tr><th>Featured</th></tr>
  </thead>
  <tbody>
    <?php foreach ($packages as $package) : ?>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" class="shownCheckbox" id="<?php echo $package->id ?>" data-toggle="toggle">
          </div>
        </td>
      </tr>
    <?php endforeach ?>
  </tbody>
</table>

<Script>
  $('#table-list-tour').DataTable();

  $(".toggle-group").click(function(){
    var selectedCheckBox = $(this);

    var id        = selectedCheckBox.parent().children('input').attr('id');
    var isChecked = selectedCheckBox.is(':checked');

    $.ajax({
      url         : 'A_LINK',
      type        : 'post',
      data        : {'id':id},
      success:function(data)
      {
        console.log(data);
        if (isChecked && data !== '') {
          selectedCheckBox.attr('checked', false);
          alert(data);
        }
      },
      error:function()
      {
        alert('Toggle Failed !');
      }
    });
  });
</script> 

The problem is, in page 1, the AJAX in bootstrap toggle event works perfectly, when i move to page 2, all the ajax did not work at all, why ?

1 Answer 1

3

CAUSE

Pages other than first do not exist in DOM at the time of initialization, that is why your handler never gets called.

SOLUTION

You need to use event delegation by providing selector as a second argument in on() call, see example below:

$(document).ready(function(){
    $('#table-list-tour').DataTable();

    $('#table-list-tour').on('click', '.toggle-group', function(){
        // ... skipped ...
    });   
});

From jQuery on() method documentation:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah ~, Thanks for the solution. Kinda new to Jquery, i search for click function on google and it just return click(). Anyway, thanks for the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.