Reputation: 407
I made this following function :
function populatetable(){
$.ajax({
type: 'GET',
url: 'backend/conn.php?action=populatetable'
}).done(function(data){
var response = data.data;
$.each(response, function(key, element){
row += '<tr> <<td>' + element.phone + '</td> <td> <button class="trigger"> Edit Data </button> </td> </tr>';
});
$('table.loadeddata > tbody').html(row);
})
}
and stored it to a file called script.js
. Then in another file named index.php
I included that file within the tag <script src='script.js'></script>
and below the above script tag, I made once again a <script>
and put this following code into the second <script>
tag :
$('document').ready(function(){
populatetable();
$('button.trigger').click(function(){
window.alert('button works');
});
});
why did the button not showing the alert
when clicked?
The button appeared perfectly, it seems that the closure caused the problem but I'm not sure.
Upvotes: 1
Views: 36
Reputation: 1283
the button is dynamically created, so it is not in the DOM at load time. try:
$('body').on('click', '.trigger', function(){
window.alert('button works');
});
fiddle https://jsfiddle.net/sn36oyfo/
Read more about event delegation
Upvotes: 1