diff --git a/js-essentials/form-autosave-single-entry/README.md b/js-essentials/form-autosave-single-entry/README.md new file mode 100644 index 0000000..664a890 --- /dev/null +++ b/js-essentials/form-autosave-single-entry/README.md @@ -0,0 +1,9 @@ +# Form Autosave + +We're going to write a script that automatically saves form field data +as a user types. + +# Reference + +* https://leanwebclub.com/learn/js-essentials/project-form-autosave/ + diff --git a/js-essentials/form-autosave-single-entry/index.html b/js-essentials/form-autosave-single-entry/index.html new file mode 100644 index 0000000..78dff38 --- /dev/null +++ b/js-essentials/form-autosave-single-entry/index.html @@ -0,0 +1,32 @@ + + + + + + + Form Autosave + + +

Form Autosave

+ +
+ + + + + + + + + + + + +

+ +

+
+ + + + diff --git a/js-essentials/form-autosave-single-entry/script.js b/js-essentials/form-autosave-single-entry/script.js new file mode 100644 index 0000000..6494599 --- /dev/null +++ b/js-essentials/form-autosave-single-entry/script.js @@ -0,0 +1,23 @@ +let selector = '#save-me input, #save-me textarea'; +let form = document.querySelector('form#save-me'); +let formElements = document.querySelectorAll(selector); +let prefix='autosave_'; +let entryName = prefix+form.id; +let entry = JSON.parse(localStorage.getItem(entryName)) || {}; + +window.addEventListener('input', function (event) { + if (event.target.matches(selector)) { + entry[event.target.id] = event.target.value; + localStorage.setItem(entryName, JSON.stringify(entry)); + } +}); + +form.addEventListener('submit', function () { + localStorage.removeItem(entryName); +}); + +formElements.forEach( function (element) { + let value = entry[element.id]; + + if (value != null) element.value = value; +}); diff --git a/js-essentials/main.go b/js-essentials/main.go index 01011c9..b2da93f 100644 --- a/js-essentials/main.go +++ b/js-essentials/main.go @@ -24,6 +24,7 @@ func main() { mux.Handle("GET /monster-game/", http.StripPrefix("/monster-game", http.FileServer(http.Dir("monster-game")))) mux.Handle("GET /monster-game-score/", http.StripPrefix("/monster-game-score", http.FileServer(http.Dir("monster-game-score")))) mux.Handle("GET /form-autosave/", http.StripPrefix("/form-autosave", http.FileServer(http.Dir("form-autosave")))) + mux.Handle("GET /form-autosave-single-entry/", http.StripPrefix("/form-autosave-single-entry", http.FileServer(http.Dir("form-autosave-single-entry")))) log.Println("Start the web server...") err := http.ListenAndServe(":8080", mux)