const btnToDoInfo = document.getElementById("btnToDoInfo");
var arrayToDo = [];
btnToDoInfo.addEventListener("click", ToDoFunc);
function ToDoFunc()
{
var ToDoTask = document.getElementById("Task-Dropdown").value;
var ToDoModCode = document.getElementById("ModuleCode-Dropdown").value;
var ToDoDescription = document.getElementById("Description").value;
const d = new Date();
let timeStamp = d.getTime();
const arrayOfObjects =
[{TaskName: ToDoTask, ToDoModCode: ToDoModCode, Description: ToDoDescription ,UniqueID: timeStamp}]
arrayToDo.push(arrayOfObjects);
//Add task and Module to the table
var ToDoTable = document.getElementById("ToDo-Table");
var rowCnt = ToDoTable.rows.length -1;
var row = document.createElement("tr");
row = ToDoTable.insertRow(rowCnt);
row.setAttribute("onclick","myFunction(this)");
console.log(row.attributes);
var ModuleCodeRow = row.insertCell(0);
var TaskRow = row.insertCell(1);
var DescriptionRow = row.insertCell(2);
var TimeRow = row.insertCell(3);
TaskRow.innerHTML = ToDoTask;
ModuleCodeRow.innerHTML = ToDoModCode;
DescriptionRow.innerHTML = ToDoDescription;
}
function myFunction(x){
var i = x.rowIndex
document.getElementById("ToDo-Table").deleteRow(i);
}
HTML The following is my HTML for the specific table in question
<h1>To do list</h1>
<label for = "ModuleCode-Dropdown">Module Code</label>
<select name="Module-Codes" id = "ModuleCode-Dropdown"></select><br><br>
<label for = "Task-Dropdown">Task</label>
<select name="Task" id = "Task-Dropdown"></select><br><br>
<label for = "Description">Description</label>
<input type="text" id = "Description"><br><br>
<input type = "button" class = "add" id = "btnToDoInfo" value = "Add"><br><br>
<!--A table where the output is shown-->
<table class = "ToDo" id = "ToDo-Table">
<tr>
<th>Module Code</th>
<th>Task</th>
<th>Description</th>
<th>Due Date</th>
</tr>
<tr>
<td id = "ModuleCode-Content"></td>
<td id = "Task-Content"></td>
<td id = "Description-Content"></td>
<td id = "DueDate-Content"></td>
</tr>
</table>
I dynamically created table rows with a attribute of onclick but when I run the code I receive the following error
Uncaught ReferenceError: myFunction is not defined at HTMLTableRowElement.onclick. I cannot use jQuery.
I want the table row I click on to be deleted.
CodePudding user response:
You should add an event listener to the row element as follows:
row.addEventListener("click", myFunction);
and change myFunction to:
function myFunction() {
this.remove();
}
CodePudding user response:
try finding the element and select it within a variable, for example:
var element = document.querySelector('#id');
and then remove it using:
element.parentNode.removeChild(element);