I am developing a simple website in HTML and trying to implement a delete function in JavaScript that takes an id value passed within the onClick parameters. It is then concatenated with API URIs to delete from a database. When the onClick event executes the id value is changed and I cannot understand why.
The getImages() function retrieves data from the API and appends it to a list, adding the delete button for each image.
An example id when fetched for the getImages() function shows in the console log: 637767724469985182
function getImages(){
$('#ImageList').html('<div class="spinner-border" role="status"><span class="sr-only">
</span>');
$.getJSON(IMAGERAA, function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log(val["id"]);
items.push('<button type="button" id="deleteAsset" class="btn btndanger"
onclick="deleteAsset('+val["id"] +')">Delete</button> <br/><br/>');
items.push( "<hr />");
});
$('#ImageList').empty();
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#ImageList" );
});
}
The console log then shows that the id when passed to the delete function has changed to 637767724469985200.
function deleteAsset(id){
console.log(id);
$.ajax({
type: "DELETE",
url: IMAGEDIA1 + id + IMAGEDIA2,
}).done(function( msg ) {
getImages();
});
}
You are missing a set of quotes around the string passed into deleteAsset() in the html
Try changing:
onclick="deleteAsset('+val["id"] +')"
to
onclick="deleteAsset(\"'+val["id"] +'\")"