Last active
August 29, 2015 14:05
-
-
Save austinlyons/c8fce27428824f877ed7 to your computer and use it in GitHub Desktop.
Adding delete functionality to eloquentjavascript's localStorage example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Notes: <select id="list"></select> | |
<button onclick="addNote()">new</button> | |
<button onclick="deleteNote()">delete</button><br> | |
<textarea id="currentnote" style="width: 100%; height: 10em"> | |
</textarea> | |
<script> | |
var list = document.querySelector("#list"); | |
function addToList(name) { | |
var option = document.createElement("option"); | |
option.textContent = name; | |
list.appendChild(option); | |
} | |
// Initialize the list from localStorage | |
var notes = JSON.parse(localStorage.getItem("notes")) || | |
{"my first note": ""}; | |
for (var name in notes) | |
if (notes.hasOwnProperty(name)) | |
addToList(name); | |
function saveToStorage() { | |
localStorage.setItem("notes", JSON.stringify(notes)); | |
} | |
var current = document.querySelector("#currentnote"); | |
current.value = notes[list.value] || ""; | |
list.addEventListener("change", function() { | |
current.value = notes[list.value]; | |
}); | |
current.addEventListener("change", function() { | |
notes[list.value] = current.value; | |
saveToStorage(); | |
}); | |
function addNote() { | |
var name = prompt("Note name", ""); | |
if (!name) return; | |
if (!notes.hasOwnProperty(name)) { | |
notes[name] = ""; | |
addToList(name); | |
saveToStorage(); | |
} | |
list.value = name; | |
current.value = notes[name]; | |
} | |
function removeFromStorage(key) { | |
delete notes[key]; | |
} | |
function removeFromDropdown(idx) { | |
list.remove(idx); | |
} | |
function deleteNote() { | |
var selected = list.selectedIndex; | |
if (selected >= 0) { | |
removeFromStorage(list[list.selectedIndex].text); | |
removeFromDropdown(list.selectedIndex); | |
saveToStorage(); | |
current.value = notes[list.value] || ""; | |
} | |
} | |
</script> |
Author
austinlyons
commented
Aug 19, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment