Skip to content

Instantly share code, notes, and snippets.

@geoffreycrofte
Created December 10, 2022 17:54
Show Gist options
  • Save geoffreycrofte/5c0c122bbab270b281fbe2b154b30abf to your computer and use it in GitHub Desktop.
Save geoffreycrofte/5c0c122bbab270b281fbe2b154b30abf to your computer and use it in GitHub Desktop.
JavaScript class that saves form input data to local storage, using the input element's ID attribute as the key, and providing methods for retrieving and populating the data:
/**
* Code Generated by an AI
* Never tested in production, the goal is to store it as Gist before I can try this in a real web project.
*/
class FormDataStore {
// Constructor function to set up the data store
constructor() {
this.data = {};
}
// Method to save the form data to local storage
saveData(form) {
// Get all of the form inputs
const inputs = form.querySelectorAll('input, textarea, select');
// Loop through the inputs and save their data
inputs.forEach((input) => {
const inputType = input.getAttribute('type');
let value;
// Handle the input type
switch (inputType) {
case 'radio':
if (input.checked) {
value = input.value;
}
break;
case 'checkbox':
value = input.checked;
break;
default:
value = input.value;
break;
}
// Save the input value to the data store
if (value !== undefined) {
this.data[input.id] = value;
}
});
// Save the data store to local storage
localStorage.setItem('form_data', JSON.stringify(this.data));
}
// Method to load the form data from local storage
loadData() {
// Retrieve the data from local storage
const data = JSON.parse(localStorage.getItem('form_data'));
// Loop through the data and populate the form inputs
for (const key in data) {
if (data.hasOwnProperty(key)) {
const input = document.getElementById(key);
const inputType = input.getAttribute('type');
// Handle the input type
switch (inputType) {
case 'radio':
if (input.value === data[key]) {
input.checked = true;
}
break;
case 'checkbox':
input.checked = data[key];
break;
default:
input.value = data[key];
break;
}
}
}
}
}

To use this class, you would first create a new instance of the FormDataStore class. Then, you can call the saveData method to save the form input data to local storage, and call the loadData method to populate the form inputs with the saved data. Here is an example of how you might use the FormDataStore class in your code:

// Create a new instance of the FormDataStore class
const formData = new FormDataStore();
// Save the form data to local storage when the form is submitted
const form = document.getElementById('my-form');
form.addEventListener('submit', (event) => {
formData.saveData(form);
});
// Load the form data from local storage when the page loads
formData.loadData();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment