Loading lesson path
Formula
To - Do List.You will add tasks, remove tasks, and clear all tasks.
Array in localStorage.
How to save and load data using localStorage
First create an HTML page with: An input field wid id="task" A button for calling addTask() A unordered list with id="list" A button for calling clearAll()
<!DOCTYPE html> <html> <body>
Formula
< h2 > To - Do List </h2 ><input id="task" placeholder="New task"> <button onclick="addTask()">Add</button> <ul id="list"></ul> <button onclick="clearAll()">Clear All</button> <script>
// Create a task Array let tasks = [];</script> </body> </html>
The displayTasks() function updates and displays the list.
// Function to display the list function displayTasks() {
let html = "";
for (let i = 0; i < tasks.length; i++) {
html += "<li>" + tasks[i] +
" <button onclick='removeTask(" + i + ")'>x</button></li>";
}
document.getElementById("list").innerHTML = html;
}
The displayTasks() function should be called whenever the list changes.// Function to Add a task function addTask() {
let taskInput = document.getElementById("task");
let text = taskInput.value;
if (text === "") {
return;
}
tasks.push(text);
taskInput.value = "";
saveTasks();
displayTasks();
}// Function to Remove a task function removeTask(i) {
tasks.splice(i, 1);
saveTasks();
displayTasks();
}
The Array method splice(i, 1) removes 1 item at position i.function removeTask(i) {
tasks.splice(i, 1);
saveTasks();
displayTasks();
}// Function to Save tasks function saveTasks() {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
To store arrays in localStorage, we convert them to text using JSON.stringify().