I'm making a todo list using JSONPlaceholder. Everything works fine (at least at the moment), but when I delete the selected <li>, the next <li> gets deleted.
I know it's because I did it by .splice(id - 1, 1) in deleteTodo. I know I should get the right index of the item which has the ID of the selected item instead of selectedItem, but I don't know how to get it. Probably, I'll have to use findIndex() but I can't think of the function to give as the parameter.
Any help will be appreciated.
todoList = {
todos: [],
removeClick: function (icon) {
let selectedIndex = icon.parentElement.parentElement.dataset.index;
todoList.deleteTodo(selectedIndex);
},
deleteTodo: function (index) {
var id = index;
$.ajax({
url: `https://jsonplaceholder.typicode.com/todos/${id}`,
type: 'delete',
success: function () {
todoList.todos.splice(id - 1, 1);
todoList.displayTodo();
}
})
},
displayTodo: function () {
$ul.innerHTML = "";
let innerContents = '';
for (let i = 0; i < this.todos.length; i++) {
let todo = this.todos[i];
let className = 'completed'
let checked = 'checked'
if (todo.completed === false) {
className = "";
checked = "";
}
innerContents += `
<li data-index="${todo.id}">
<div class="checkboxDiv">
<input type="checkbox" class="checkbox" data-key="checkbox"
${checked} />
</div>
<div class="contents ${className}" data-key="contents">
${todo.title}
</div>
<div class="icondiv">
<i class="far fa-edit" data-key="icon_edit"></i>
<i class="far fa-trash-alt" data-key="icon_trash"></i>
</div>
</li>
`;
}
$ul.innerHTML = innerContents;
}
};
todoList.getData();
$ul.addEventListener('click', (e) => {
switch (e.target.dataset.key) {
case "icon_trash":
todoList.removeClick(e.target);
break;
}
});