Edit an Existing Task
Edit an Existing Task
Now let users change a task after it has been created. For this first editing version, reuse the existing task inputs. The custom edit modal will replace this interaction later in the course.
1. Add an Edit action
In the task markup generated by renderTasks(), add an edit button and attach the task ID to it:
<button
type="button"
class="task-action"
data-action="edit"
data-id="${task.id}"
>
Edit
</button>
Use the prepared button class from your starter project if it differs.
2. Find the task to edit
Add an edit handler that looks up the selected task:
function startEditing(taskId) {
const task = tasks.find((item) => item.id === taskId);
if (!task) {
return;
}
document.getElementById("task-input").value = task.title;
document.getElementById("due-input").value = task.due || "";
priorityDropdown.value = task.priority || "Medium";
}
For this lesson, the existing add controls become the editing controls after the Edit action is chosen. You can use a small editingTaskId variable to remember which task is being changed.
3. Save the edited values
Create an editing state near your other task-list state:
let editingTaskId = null;
When editing starts, store the ID:
editingTaskId = task.id;
Then update your add-task handler so it changes the existing task when editingTaskId is set:
if (editingTaskId !== null) {
const task = tasks.find((item) => item.id === editingTaskId);
if (task) {
task.title = title;
task.due = dueInput.value;
task.priority = priorityDropdown.value;
}
editingTaskId = null;
} else {
tasks.push({
id: crypto.randomUUID(),
title,
due: dueInput.value,
priority: priorityDropdown.value,
completed: false
});
}
Keep the existing reset-and-render steps after this logic.
4. Test editing
Create a task, give it a due date and priority, choose Edit, change the values, and save.
Confirm that the same task changes instead of a second task being created.
Checkpoint: You can select an existing task, change its title, due date, and priority, and see the updated values in the task list.