xanderlopez
xanderlopez

Reputation: 657

Add new row to DataTable with td that has buttons

I can dynamically add a row to DataTable via fnAddData. Upon adding a new row, a td with an edit button that has a btn-edit. I intend to use btn-edit as a selector but I was unable to call it upon click.

HTML

<button id="add-row">Add Row</button>

<table id="example" class="display" cellspacing="0" width="100%">
 <thead>
  <tr>
   <th>Name</th>
   <th>Position</th>
   <th>Action</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Tiger Nixon</td>
   <td>System Architect</td>
   <td><button class='btn-edit' btn-id='1'>Edit</button></td>
  </tr>
  <tr>
   <td>Garrett Winters</td>
   <td>Accountant</td>
   <td><button class='btn-edit' btn-id='2'>Edit</button></td>
  </tr>
 </tbody>
</table>

jQuery

$(document).ready(function() {
 $('#example').DataTable();

 var obj = {3: {'name':'Rose','position': 'VP'}, 4: {'name':'Jack','position': 'Captain'}};

 var count = 3;
 $('#add-row').on('click',function() {
  $('#example').dataTable().fnAddData( [
   obj[count].name,
   obj[count].position,
   "<button class='btn-edit' btn-id='"+count+"'>Edit</button>" 
  ]).draw();
  count++;
 });

 $('.btn-edit').click(function() {
  alert($(this).attr('btn-id'));
 });
});

https://jsfiddle.net/33Lbayx3/2/

Upvotes: 1

Views: 1979

Answers (1)

Hassan ALi
Hassan ALi

Reputation: 1331

thats how you can call a dynamically created DOM element.

   $(document).ready(function() {
         $('#example').DataTable();

         var obj = {3: {'name':'Rose','position': 'VP'}, 4: {'name':'Jack','position': 'Captain'}};

         var count = 3;
         $('#add-row').on('click',function() {
          $('#example').dataTable().fnAddData( [
           obj[count].name,
           obj[count].position,
           "<button class='btn-edit' btn-id='"+count+"'>Edit</button>" 
          ]).draw();
          count++;
         });
         $(document).on("click",".btn-edit",function(){

         alert(1);
         })  

        });

you can test working

Upvotes: 1

Related Questions