0

I am creating a table using the datatable plugin. Have added buttons to last column of the table. Issue: The button's on click is not triggered.

Javascript where table is created.

<script>
  $(document).ready(function() {
    $('#tagtbl').DataTable( {
        "paging": false,
        "info": false,
        "searching": false,
        "ajax": "../api/clienttagtbl.php?off=OFF002",
        "rowId": "id",
        "columns": [
            { "data": "tagname" },
            { "data": null, "defaultContent": '<button id="tagdelete" type="button" class="btn btn-danger btn-sm" >X</button>' }
        ]
    } );
  } );
</script>

Javascript where On click is called

<script>
$(document).ready(function() {
  $('#tagdelete').click( function(){
    console.log("hi"); // <<---This is not working
  });
  $('#tagtbl').click( function(){
    console.log("hi2");  //<<---This is working
  });
});
</script>

HTML

    <table id="tagtbl" class="table table-sm" >
      <thead>
        <tr>
          <th>Tag Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>Tag Name</th>
          <th></th>
        </tr>
      </tbody>
    </table>

HTML Table

2 Answers 2

3

Try this

 $('#tagtbl').on('click','.tagdelete' function(){
    console.log("hi");
  });

i recommend you use a class for all the buttons instead of using id.

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

3 Comments

Give a class to the buttons and use the above code.
Any insights on why my method is not working. I am very new to jQuery
Could you just search for event delegation in jquery. That would give you enough idea about your issue.
1

you need to add the button click in datatable drawCallback function

$('#example').dataTable( {
    "drawCallback": function( settings ) {
       $('#tagdelete').click( function(){
    console.log("hi");
  });
  $('#tagtbl').click( function(){
    console.log("hi2");
  });
    }
} );

Comments

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.