0

I have a dataTables where each row has a number input form. When you click the input form, buttons will appear. However, it only works in the first 10 entries. After that, (searching, next page, sorting, etc), it wont. Is there anything I am doing wrong? How can I fix this?

CSS

 echo '<td>
      <div class="row">
      <div class="col-sm-3">
      <a href="#" class="btn btn-danger btn-circle btn-sm one" style="display:none;">
      <i class="fas fa-times"></i>
      </a>
      </div>
      <div class="col-sm-6">
      <div class="test">
      <input type="number" class="form-control" value="'.$row["prod_count"].'">
      </div></div>
      <div class="col-sm-3">      
      <a href="#" class="btn btn-success btn-circle btn-sm two" style="display:none;">
      <i class="fas fa-check"></i>
      </a></div></div> </td>';

JQUERY

    <script>
  $(document).ready(function(){
  $('.test').click(function(){
    $(this).closest("td").find(".one").toggle(200);
    $(this).closest("td").find(".two").toggle(200);
  })
})

</script>
  • 1
    DataTables.js rebuilds the HTML each time you page/sort/etc - so those `'test` buttons will not longer exist. You could hook into the datatable redraw or you could use event delegation: `$(document).on("click", ".test", function() {` – freedomn-m May 09 '20 at 15:57
  • You're adding the div dynamically to the page, therefore the click() event has to be delegated from a parent element that's already there when the page is initially loaded to this div, e.g. from document, using on(): $(document).on("click", ".test", function() { });: For more info, check https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – matthias_h May 09 '20 at 15:57
  • @freedomn-m I tried what you suggested however, everytime I click, the toggle adds +1. E.g. when I clicked for the fourth time, the buttons toggle 4 times. – Karla Romero May 09 '20 at 16:08
  • Then you didn't implement it the way I suggested - or you have some other code: only replace `$('.test').click(function(){` with `$(document).on("click", ".test", function() {` – freedomn-m May 09 '20 at 16:09
  • @freedomn-m Its working now, thank you!! – Karla Romero May 09 '20 at 16:14

0 Answers0