Reputation: 614
I'm having an issue trying to setup a row where by when the remove button is pressed, the row is removed from the table. When I set the onclick method as shown below, it will automatically remove the row upon creation of it. I assume it's calling the function
I've seen that you should remove the parenthesis when assigning such and that's causing the issue. But for obvious reasons I require the rows id to be able to remove the row.
name = "thomas";
foo = "foo";
bar = "bar";
// Create a new row
var row = table.insertRow();
row.id = name;
// Create cells with requested information
row.insertCell().innerText = name;
row.insertCell().innerText = foo;
row.insertCell().innerText = bar;
var removeButton = document.createElement("BUTTON");
removeButton.innerHTML = "Remove";
removeButton.onclick = deleteRow(row.id);
var removeButtonCol = row.insertCell();
removeButtonCol.appendChild(removeButton);
function deleteRow(rowID)
{
var row = document.getElementById(rowID);
row.parentNode.removeChild(row);
}
So how can I resolve this? I don't know how to setup an onclick for a function that requires parenthesis or an eaiser way to pass the row id when a button is pressed that belongs to a rwo
Upvotes: 1
Views: 1336
Reputation: 614
So it turns out I should be using an event listener instead of the onclick method.
EG, where we did onclick:
var removeButton = document.createElement("BUTTON");
removeButton.innerHTML = "Remove";
removeButton.addEventListener('click', function () {
deleteRow(row.id)
});
This works perfectly
Upvotes: 1