Last active
February 22, 2022 01:39
-
-
Save Clintronix/cf5e228578f1aced7f915066fc5ce95f to your computer and use it in GitHub Desktop.
Autosave - Single Entry
This file contains hidden or 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
| <html> | |
| <body> | |
| <style> | |
| body { | |
| margin: 1em auto; | |
| max-width: 40em; | |
| width: 88%; | |
| } | |
| label, | |
| input, | |
| textarea { | |
| display: block; | |
| width: 100%; | |
| } | |
| input, | |
| textarea { | |
| margin-bottom: 1em; | |
| } | |
| textarea { | |
| height: 8em; | |
| } | |
| </style> | |
| <form id="save-me"> | |
| <label for="name">Name</label> | |
| <input type="text" name="name" id="name"> | |
| <label for="address">Address</label> | |
| <input type="text" id="address" name="address" > | |
| <label for="email">Email</label> | |
| <input type="email" id="email" name="email"> | |
| <label for="more">Additional thoughts?</label> | |
| <textarea name="more" id="more"></textarea> | |
| <p> | |
| <button type="submit">Submit</button> | |
| </p> | |
| </form> | |
| <div id="results"></div> | |
| </body> | |
| <script> | |
| const saveBtn = document.querySelector('button'); | |
| const form = document.querySelector('form'); | |
| const fields = form.elements; | |
| //for autosaving | |
| const prefix = 'autosave_'; | |
| // | |
| //Saves data to localStorage | |
| let save = function (event) { | |
| event.preventDefault(); | |
| let formData = new FormData(form); | |
| //remove autosave data | |
| for (let field of fields) { | |
| localStorage.removeItem(prefix + field.id); | |
| } | |
| //add data to storage | |
| let jsonData = JSON.stringify(formData); | |
| //console.log('json ' + jsonData); | |
| localStorage.setItem('Post-Data', jsonData); | |
| let GetData = localStorage.getItem('Post-Data'); | |
| for (let data of GetData) { | |
| console.log('GET ' + data); | |
| } | |
| //display results on page after submit | |
| results.innerHTML = `<table> | |
| <tr>Name: ${localStorage.getItem('Name')} </tr> | |
| <tr>Address: ${localStorage.getItem('Address')} </tr> | |
| <tr>Email: ${localStorage.getItem('Email')} </tr> | |
| <tr>Thoughts: ${localStorage.getItem('Thoughts')} </tr> | |
| </table>` | |
| } | |
| //autoSave localStorage | |
| let autoSave = function (event) { | |
| //get data | |
| let data = event.target.value; | |
| let id = event.target.id; | |
| //make sure element has an id | |
| if (!id) return; | |
| //store items | |
| localStorage.setItem(prefix + id, data); | |
| } | |
| form.addEventListener('input', autoSave); | |
| saveBtn.addEventListener('click', save); | |
| </script> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment