Search code examples
jquerypaginationbootstrap-table

jQuery events not listened anymore when pagination


I'm using pagination implemented in bootstrap-table, and I recently noticed that when use it, my custom jQuery script doesn't work anymore.

To be more precise, here is a snippet :

$(document).ready(function() {

  $('.form-modal-confirm-remove').click(function() {

    alert("Test");

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/locale/bootstrap-table-fr-FR.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<table data-toggle="table" data-classes="table table-hover table-condensed table-no-bordered" data-pagination="true" data-page-size="2">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        1
      </td>
      <td>
        Test
      </td>
      <td>
        <button type="button" class="btn btn-danger btn-circle form-modal-confirm-remove" data-toggle="tooltip" data-placement="top" title="Supprimer">
          <i class="fa fa-trash"></i>
        </button>
      </td>
    </tr>
    <tr>
      <td>
        2
      </td>
      <td>
        Test
      </td>
      <td>
        <button type="button" class="btn btn-danger btn-circle form-modal-confirm-remove" data-toggle="tooltip" data-placement="top" title="Supprimer">
          <i class="fa fa-trash"></i>
        </button>
      </td>
    </tr>
    <tr>
      <td>
        3
      </td>
      <td>
        Test
      </td>
      <td>
        <button type="button" class="btn btn-danger btn-circle form-modal-confirm-remove" data-toggle="tooltip" data-placement="top" title="Supprimer">
          <i class="fa fa-trash"></i>
        </button>
      </td>
    </tr>
  </tbody>
</table>

You can see that on click on remove button, an alert show up. Then, when you move to second page, the alert doesn't pop anymore.

You can go back to page 1, alert still not appear.


Solution

  • Please use .on instead of .click method. .on method will work for dynamically added elements.

    $(document).ready(function() {
    
      $(document).on('click','.form-modal-confirm-remove',function() {
    
        alert("Test");
    
      });
    
    });