Skip to content Skip to sidebar Skip to footer

Javascript Todo List Delete And Complete Buttons

My CodePen So when I click the delete and complete buttons it runs these functions function deleteListItem(){ alert('Item was deleted'); } function completeListIte

Solution 1:

In your javascript, when you declare deleteButton and completeButton they are both assigned the same element, the ul. That element contains the entire list. That is not what you want, you want to handle clicks on the buttons. deleteButton should be assigned to your delete button element and your completeButton to your complete button element. To do this, simply use the ID of the buttons you want instead of the ID of the UL.

In you code, change this:

var deleteButton = document.getElementById("todo");
deleteButton.addEventListener("click", deleteListItem);
var completeButton = document.getElementById("todo");
completeButton.addEventListener("click", completeListItem);

To this:

var deleteButton = document.getElementById("Remove");
deleteButton.addEventListener("click", deleteListItem);
var completeButton = document.getElementById("Complete");
completeButton.addEventListener("click", completeListItem);

EDIT: Since your buttons are not unique you should not use an id to add the event listener. You should use a class and assign the event listener to all the elements with the class by looping threw them. In your html add a class attribute to your buttons like this: <button class="Remove"><i class="fa fa-trash" aria-hidden="true"></i></button>. Then handle the events this way:

var deleteButtons = document.getElementsByClassName("Remove");
for (var i = 0; i < deleteButtons.length; i++) {
    deleteButtons[i].addEventListener('click', deleteListItem, false);
}
var completeButton = document.getElementsByClassName("Complete");
for (var i = 0; i < completeButton.length; i++) {
        completeButton[i].addEventListener('click', completeListItem, false);
}

Solution 2:

var deleteButton = document.getElementById("Remove");
  deleteButton.addEventListener("click", deleteListItem);
var completeButton = document.getElementById("Complete");
  completeButton.addEventListener("click", completeListItem);

Assign addEventListener to specific id of the button. idtodo is the ul so clicking anything inside ul will run both functions

Post a Comment for "Javascript Todo List Delete And Complete Buttons"