Reputation: 31
I run the program and add student to the list, then I delete this studentlist row. Then When I add new student the studentlist show me both deleted row and new inserted row? How can I solve this?
function renderStudentList() {
tableBody.innerHTML = "";
studentList.map((student) => {
const studentRow = `
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.surname}</td>
<td>${student.birthday}</td>
<td>${student.age}</td>
<td>${student.gender === "M" ? "Male" : "Female"}</td>
<td>
<img id="delete" src="./icons/delete.svg" alt="delete" onclick="deleteRow(this)">
<img id="edit" src="./icons/edit.svg" alt="edit" >
</td>
</tr>
`;
tableBody.insertAdjacentHTML("beforeend", studentRow);
});
}
addStudentBtn.addEventListener("click", (e) => {
e.preventDefault();
const newStudent = {
id: generateId(),
name: document.getElementById("name").value,
surname: document.getElementById("surname").value,
birthday: document.getElementById("birthday").value,
age: document.getElementById("age").value,
gender: document.getElementById("genderM").checked ? "M" : "F",
};
if (isDataValid(newStudent)) {
document.getElementById("student-form").reset();
studentList.push(newStudent);
renderStudentList();
} else {
console.log("PLEASE FILL THE DATA");
}
});
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("table-body").deleteRow(i - 1);
}
Upvotes: 0
Views: 120
Reputation: 45883
You are removing the row from the DOM by calling deleteRow(i - 1)
but not from the actual list inside studentList
, that's why next time you call renderStudentList()
, what you have deleted shows up.
An easy way to overcome this and that would simplify your code is to to first change renderStudentList()
so each row gets an id, like so:
function renderStudentList() {
tableBody.innerHTML = "";
studentList.map((student) => {
const studentRow = `
<tr id="${student.id}">
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.surname}</td>
<td>${student.birthday}</td>
<td>${student.age}</td>
<td>${student.gender === "M" ? "Male" : "Female"}</td>
<td>
<img id="delete" src="./icons/delete.svg" alt="delete" onclick="deleteRow(${student.id})" />
<img id="edit" src="./icons/edit.svg" alt="edit" />
</td>
</tr>
`;
tableBody.insertAdjacentHTML("beforeend", studentRow);
});
}
And deleteRwo
as below, so it removes the element from the DOM as well as from the list, by using the id that he gets while generating the template littoral:
function deleteRow(id) {
studentList = studentList.filter(student => student.id !== id);
document.getElementById(`${id}`).remove();
}
Upvotes: 1