Skip to content

Instantly share code, notes, and snippets.

@piotrkulpinski
Last active September 30, 2022 15:18
Show Gist options
  • Save piotrkulpinski/8bb14fcda98d021b86a3a670bc62b911 to your computer and use it in GitHub Desktop.
Save piotrkulpinski/8bb14fcda98d021b86a3a670bc62b911 to your computer and use it in GitHub Desktop.
Pre-populating form based on the array stored in localStorage
const storageKey = 'storage'
const serializeArray = (elements, options) => {
const serializeData = []
const defaults = {
excludeTypes: ['password', 'hidden', 'submit'],
excludeNames: [],
}
const opts = Object.assign(defaults, options)
elements.forEach((el) => {
if (opts.excludeTypes.includes(el.type) || opts.excludeNames.includes(el.name)) {
return
}
if (el.type !== 'radio' && el.type !== 'checkbox') {
serializeData.push({ name: el.name, value: el.value, type: el.type })
} else if (el.checked) {
serializeData.push({ name: el.name, value: el.value, type: el.type })
}
})
return serializeData
}
const setLocalStorage = (elements, options) => {
const formData = JSON.stringify(serializeArray(elements, options))
localStorage.setItem(storageKey, formData)
}
const initApp = (form) => {
const formData = JSON.parse(localStorage.getItem(storageKey))
if (!formData) {
return
}
formData.forEach((v) => {
if (v.type !== 'radio' && v.type !== 'checkbox') {
const input = form.querySelector(`[name=${v.name}]`)
if (input && input !== null) {
setTimeout(() => {
input.value = v.value
}, 0)
}
} else {
const input = form.querySelectorAll(`[name=${v.name}]`)
input.forEach((el) => {
if (el.name === v.name && el.value === v.value) {
setTimeout(() => {
el.checked = true
}, 0)
}
})
}
})
}
export const saveStorage = (form, options = {}) => {
try {
const elements = form.querySelectorAll('input, textarea, select')
form.addEventListener('change', () => {
setLocalStorage(elements, options)
})
elements.forEach((el) => {
el.addEventListener('keyup', () => {
console.log('keyup')
setLocalStorage(elements, options)
})
})
initApp(form)
} catch (error) {
console.error(error)
}
}
export default (element = document) => {
const forms = Array.from(element.querySelectorAll('[data-form-populate]'))
forms.forEach((form) => {
saveStorage(form, { excludeNames: ['message'] })
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment