Main JS to store Form Data in Local Storage (javascript)
This Javascript goes in an HTML Widget on the page with the source form Widget.
;(w => {
let $, $form;
const formWidjetID = 'source_form';
const localStorageVariable = 'source_form';
const inputSelctor = 'input, textarea';
const triggers = 'change';
w.addEventListener('load' , ()=>{
$ = jQuery;
init();
})
const init = () => {
$form = $('#' + formWidjetID);
const $inputs = $form.find(inputSelctor);
$inputs.on(triggers, setLocalStorage);
}
const setLocalStorage = () =>{
let json = convertFormToJSON($form.find('form'));
localStorage.setItem(localStorageVariable, JSON.stringify(json));
const event = new Event('formToLocalStorage');
w.dispatchEvent(event);
}
const clearLocalStorage = () => {
localStorage.removeItem(localStorageVariable);
}
const getValueByName = name => {
const vars = localStorage.getItem(localStorageVariable);
const obj = JSON.parse(vars);
const fieldName = 'form_fields[' + name + ']';
return obj[fieldName]? obj[fieldName] : "";
}
const convertFormToJSON = $form => {
const array = $form.serializeArray();
const json = {};
$.each(array, function () {
json[this.name] = this.value || "";
});
return json;
}
//Make getter function available to Window
window._formToLocal = {
getValueByName: getValueByName,
clearLocalStorage: clearLocalStorage
}
})(window);
JS for Page Element Update Test (javascript)
Place this in another HTML Widget. Below the element you want to update
;(w => {
let $,
varName = 'name',
targetSelector = '#target_heading_for_name h2',
$target;
w.addEventListener('DOMContentLoaded', ()=>{
$ = jQuery;
$target = $(targetSelector);
})
w.addEventListener('formToLocalStorage', ()=>{
const val = w._formToLocal.getValueByName(varName);
$target.text(val)
});
})(window);
JS for the Popup (javascript)
Place this in an HTML Widget on the Popup
console.log('INIT');
;( w => {
const $ = jQuery;
const varName = 'name';
const targetSelector = '#target_name h2';
const $target = $(targetSelector);
const val = w._formToLocal.getValueByName(varName);
$target.text(val);
})(window);