Last active
August 6, 2025 12:05
-
-
Save deanebarker/8fca8b071ba4c5135e4ee0f195371155 to your computer and use it in GitHub Desktop.
Saves and populates form elements from local storage
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
| /* | |
| Just put a "data-storage-key" attribute on your form fields: | |
| <input name="authkey" data-storage-key="saved_auth_key"/> | |
| The value can be anything that is a valid key in localStorage (stick with mostly strings and you'll be fine). | |
| When the form submits, whatever is in the field will be saved to local storage under the provided key name. | |
| Next time the page loads, that form field will be populated from local storage. | |
| I use this for API keys and other config data that I want submitted every time, but I don't want have to populate every time. | |
| */ | |
| document.addEventListener("DOMContentLoaded", () => { | |
| // Bind to every form submit and save the value of any field with a data-storage-key attribute | |
| for (const form of document.querySelectorAll("form")) { | |
| form.addEventListener('submit', (f) => { | |
| for (const savedField of form.querySelectorAll("*[data-storage-key]")) { | |
| localStorage.setItem(savedField.dataset.storageKey, savedField.value); | |
| } | |
| }) | |
| } | |
| // Find anything with a data-storage-key attribute and populate it from local storage | |
| for (const field of document.querySelectorAll("*[data-storage-key]")) { | |
| field.value = localStorage.getItem(field.dataset.storageKey) ? ? ''; | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment