I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.
'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
but it leaves me an error saying the test function isn't defined.
here's my whole code:
$.ajax({
type: "POST",
url: "../php_scripts/getUnits.php",
success: function(data){
var items = JSON.parse(data);
/*var btnSomething = $("<button>")
.attr('class', 'btn btn-danger')
.attr('id', 'asdf')
.html('Save');
*/
//$('#content').append(btnSomething);
for (var i = 0; i < items.length; i++) {
//test();
$('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
'<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
'<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
'</td></tr>');
}
function test(){
alert('test');
}
/*$(document).on("click", "#btnHistory", function(){
alert ('History clicked ');
});*/
}
});