Skip to content

Instantly share code, notes, and snippets.

@austinlyons
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save austinlyons/c8fce27428824f877ed7 to your computer and use it in GitHub Desktop.

Select an option

Save austinlyons/c8fce27428824f877ed7 to your computer and use it in GitHub Desktop.

Revisions

  1. austinlyons renamed this gist Aug 19, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. austinlyons created this gist Aug 19, 2014.
    67 changes: 67 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    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>