1

I am using jquery datatable with an action column. In that action column there is two links "edit" and "delete". My table is populating correctly with this action column. But problem is I need to open a bootstrap modal with a from when I click on the edit button of this datatable. But its not open my modal.

This is how I create my action column in datatable:

var myTable = 
$('#view_user_table')
.DataTable({
  bAutoWidth: false,    
  "bProcessing": true,
  "bServerSide": true,
  "sAjaxSource": "includes/process_view_bank_datatable.php",
  "aoColumnDefs": [{
                    "aTargets": [6],  
                    "bSortable": false,
                    "mData": "0",   
                    "mRender": function (data, type, full) {
                       return '<div class="hidden-sm hidden-xs action-buttons">' + 
                                '<a class="green edit_this_user" href="javascript:void(0)" data-bank_id="'+data+'">edit</a>' + 
                                '<a class="red" href="javascript:void(0)">delete</a>' + 
                              '</div>';                              
                    }
                  }
                ],
  "aaSorting": [],
  "iDisplayLength": 50,

  select: {
    style: 'multi'
  }
});

Then I tried to open my modal with click on the edit link I have created above.

This is how I tried it:

$('.edit_this_user').on('click', function() {
  alert('modal')  
}); 

But I cannot get the alert. Can anybody tell me what is the reason to its not working?

Note: I can not get any error in my console.

user3733831
  • 2,886
  • 9
  • 36
  • 68
  • 1
    Possible duplicate of [Jquery adding event listeners to dynamically added elements](http://stackoverflow.com/questions/12065329/jquery-adding-event-listeners-to-dynamically-added-elements) – aeryaguzov Nov 24 '15 at 12:48
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – TylerH Nov 26 '15 at 02:13

2 Answers2

2

The event binding for the dynamic generated elements, you should write in such a way that the parent content which has already present .on, then the event type then the element selector on which you want to trigger the event. Change the trigger code like this and try:

  $('#view_user_table').on('click', '.edit_this_user', function(){

  });
Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
1

Your code does not work, because you're trying to attach event listener to html that does not exist yet.

You create .edit_this_user dynamically (via another script, in your example it is Datatable plugin), so when document is loaded(I suppose you're code executed on load) there is no element with such class.

There are many questions about this, check them for proper explanation:

Community
  • 1
  • 1
aeryaguzov
  • 1,143
  • 1
  • 10
  • 21