Advertisement
geminilabs

[site-reviews] Autosave form values

Nov 5th, 2024 (edited)
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. document.addEventListener('DOMContentLoaded', () => {
  2.     if ('undefined' === typeof window.GLSR) return;
  3.     const storeKey = (el) => 'checkbox' === el.type ? (el.name + el.value) : el.name;
  4.     const event = (ev) => sessionStorage.setItem(storeKey(ev.target), ev.target.value);
  5.     // const forget = (el) => el.removeEventListener('change', event);
  6.     const listen = (el) => el.addEventListener('change', event);
  7.     const restore = (el) => {
  8.         const value = sessionStorage.getItem(storeKey(el));
  9.         if (null === value) return;
  10.         if (['checkbox','radio'].includes(el.type)) {
  11.             el.checked = (el.value === value);
  12.         } else {
  13.             el.value = value;
  14.         }
  15.         el.dispatchEvent(new Event('change'))
  16.     };
  17.     GLSR.Event.on('site-reviews/loaded', () => {
  18.         GLSR.forms.forEach(o => [...o.form.elements].forEach(el => {
  19.             if (el.disabled || el.readonly || ['file','hidden','password','submit'].includes(el.type)) return;
  20.             if (['input','select','textarea'].includes(el.localName)) {
  21.                 restore(el)
  22.                 listen(el)
  23.             }
  24.         }))
  25.     })
  26.     GLSR.Event.on('site-reviews/form/handle', (response) => {
  27.         if (true === response.success) {
  28.             sessionStorage.clear()
  29.         }
  30.     })
  31. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement