Reputation: 1
Title is pretty self-explanatory; I'm trying to add a delete button to each row of a table, but right now it's deleting the table headers instead of the actual row. This is the Javascript; any tips?:
function addRow() {
var table = document.getElementById("todayTasks");
var row = document.createElement('tr');
row.id = "new_add";
var td0 = document.createElement("INPUT");
td0.type = "checkbox";
td0.id = "checkbox";
td0.onchange = updateItem;
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement("input");
td3.type = "button";
td3.value = "Delete";
td3.onclick = deleteFn;
if (document.getElementById('task').value === "") {
alert("Please provide a task.");
} else if (document.getElementById('duration').value === "") {
alert("Please provide a duration.");
} else {
td1.innerHTML = document.getElementById('task').value;
td2.innerHTML = document.getElementById('duration').value;
row.appendChild(td0);
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].insertBefore(row, table.children[0].childNodes[1]);
}
function updateItem() //Cross out when checked
{
if (document.getElementById("checkbox").checked) {
document.getElementById("new_add").style.textDecoration = "line-through"
} else {
document.getElementById("new_add").style.textDecoration = "none"
}
}
function deleteFn(x) {
var i = x.rowIndex;
document.getElementById("todayTasks").deleteRow(i);
}
Upvotes: 0
Views: 49
Reputation: 21
Your delete function take an event as an argument, that event hold a reference to the element via its property target. you can than get the tr which is the parent element of your input (if you wrap the input inside a td it would be the grand parent), then you can juste remove this element from the table
function deleteFn(event) {
var input = event.target;
var currentRow = input.parentNode;
document.getElementById("todayTasks").removeChild(currentRow);
}
Upvotes: 1