Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Save data in localStorage using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Save data in localStorage using JavaScript</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form id="note-form">
<input id="note-input" type="text" placeholder="+ Add Note" required />
<button id="note-submit">Save</button>
</form>
<ul id="notes"></ul>
<script>
const noteForm = document.getElementById("note-form");
const noteInput = document.getElementById("note-input");
const noteSubmit = document.getElementById("note-submit");
const notes = document.getElementById("notes");
let notesStorage = localStorage.getItem("notes")
? JSON.parse(localStorage.getItem("notes"))
: [];
noteForm.addEventListener("submit", (e) => {
e.preventDefault();
notesStorage.push(noteInput.value);
localStorage.setItem("notes", JSON.stringify(notesStorage));
listBuilder(noteInput.value);
noteInput.value = "";
});
const listBuilder = (text) => {
const note = document.createElement("li");
note.innerHTML = text + ' <button onclick="deleteNote(this)">x</button>';
notes.appendChild(note);
};
const getNotes = JSON.parse(localStorage.getItem("notes"));
getNotes.forEach((note) => {
listBuilder(note);
});
const deleteNote = (btn) => {
let el = btn.parentNode;
const index = [...el.parentElement.children].indexOf(el);
notesStorage.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesStorage));
el.remove();
};
</script>
</body>
</html>
@w3collective

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented May 31, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment