I want a click event in the table when I am generating a dynamic table. I tried it like this.
var cartItem=[{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button Henley placket, The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}}]
function getcartDetails() {
document.getElementById("cartItemShow").innerHTML = "";
for (var get in cartItem) {
var tr = document.createElement("tr");
var tdTitle = document.createElement("td");
var tdImage = document.createElement("td");
var tdDel = document.createElement("td");
var img = document.createElement("img");
var button = document.createElement("button");
// ===============================================
img.src = cartItem[get].image;
img.width = 70;
tdTitle.innerHTML = cartItem[get].title;
button.innerText="delete";
//button.span.onclick = "delete()"; i want apply an event
//===================================================
tdImage.appendChild(img);
tdDel.appendChild(button);
tr.appendChild(tdTitle);
tr.appendChild(tdImage);
tr.appendChild(tdDel);
console.log("this is id :" + get);
document.getElementById("cartItemShow").appendChild(tr);
}
}
getcartDetails()
/*function delete(){
alert("hello")
}*/
<div class="col-md-3">
<button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button>
<table class="table collapse" id="showTable">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Image</th>
<th scope="col">action</th>
</tr>
</thead>
<tbody id="cartItemShow"></tbody>
</table>
</div>
But I am unable to add on click event. Expected Output: After clicking on the delete button, it should appear an alert message with the string "hello".