Skip to content
Advertisement

Edit button to edit a task in a To-Do List not functioning properly

I’m making your typical to-do list practice project, which is structured in a way most of you are probably familiar with.

You have projects, and within each project the user adds tasks via a popup form. each task has a button to delete or edit the specific task.

When the user clicks edit on a task, a popup form is made visible, with all the current information for the task, which can be edited.

Upon submission of the popup form, it works as expected, updating the information, but only for the first task which is edited. Subsequent edits of different tasks also edit those which were previously edited.

I know this has to do with the event listener for submitting the popup form. The function in which the event listener is declared accepts an ID as an argument that identifies the individual task which is being edited. It appears the event listener executes for all tasks on which it has previously been called.

This function is called through the click event of the edit button.

I somewhat understand what is happening here, but I’m having difficulties finding a solution.

How can I ensure the event listener for submitting the form only executes for one item at a time?

    let edit = document.createElement('button');
    edit.textContent = 'Edit';
    edit.classList.add('edit');
    edit.id = `edit-${item.id}`;
    edit.addEventListener('click', (e) => {
       let taskId = document.getElementById(e.target.id).parentNode.id;
       setEditTaskFields(taskId);
       setEditTaskEvents(taskId);
                })

function setEditTaskEvents(taskId) {
        const project = selectDisplayedProject()
        const byId = project.items.map(e => e.id);

        const task = selectDisplayedProject().items.filter(task => task.id == taskId)[0];
        document.getElementById('edit-task-form').addEventListener('submit', ()=> {
            let title = document.querySelector('#edit-task-form #title').value;
            let description = document.querySelector('#edit-task-form .description').value;
            let dueDate = document.querySelector('#edit-task-form #due-date').value;
            document.querySelectorAll('#edit-task-form .priority-container input').forEach(radio => {
                if (radio.checked) project.items[byId.indexOf(taskId)] = Item(title, description, dueDate, radio.value, selectDisplayedProject());
            });
            displayProject(selectDisplayedProject());
            document.querySelector('.edit-task-popup').style.display = 'none';
        })

Advertisement

Answer

Was able to fix it by cloning the form and removing all event listeners each time one is created.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement