SO 59110841

Link to question in output

by KooiInc MeHere

HTML

<script src="https://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>
<div class="solink" data-linkid="59110841"></div>
<div id="chkBoxes"></div>
<pre></pre>

CSS

pre {
  font-size: 1rem;
  line-height: 1.2rem;
  max-width: 500px !important;
  white-space: pre-line;
}

JavaScript

(() => {
  localStorage.setItem("Checkboxes", "{}");
  const cbDiv = document.querySelector("#chkBoxes");
  const fancyReporting = reportingFactory();
  
  // save the state of a checkbox clicked
  // used by the click handler on 'document'
  const saveCheckboxState = (val, id) => {
    localStorage.setItem("Checkboxes", 
    		JSON.stringify({
        	...JSON.parse(localStorage.getItem("Checkboxes")),
       		[`Checkbox ${id}`]: +val })
        );
    fancyReporting.showCurrentCheckboxStates();
  };
  
  // add a handler to the document
  // it's using event delegation
  document.addEventListener("click", evt =>
    // if the element has a property 'data-index', go ahead
    // otherwise do nothing
    evt.target.dataset.index && 
      saveCheckboxState(evt.target.checked, evt.target.dataset.index)
  );
  
  // create 10 checkboxes for demo
  // for every checkbox, save initial state in localStorage
  for (let i = 1; i < 11; i += 1) {
  	let cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.dataset.index = i;
    cb.title = `Checkbox ${i}`;
    cbDiv.appendChild(cb);
    // save the state using the method for it
    saveCheckboxState(0, i);
  }
  
  // just for reporting
  function reportingFactory() {
  	return {
      state: {
        checked: String.fromCharCode(9745),
        unchecked: String.fromCharCode(9744)
      },
      result: document.querySelector("pre"),
      showCurrentCheckboxStates() {
        const states2Report = Object.fromEntries(
          Object.entries(JSON.parse(localStorage.getItem("Checkboxes")))
           .map( ([key, value]) => ([key, value < 1 ? this.state.unchecked : this.state.checked]) )
        );
        this.result.textContent = `Checkboxes localStorage saved state: ${
          JSON.stringify(states2Report, null, " ")}`
          .replace(/"|{|}/g, "") + `\nlocalStorage literal value:\n${
          	JSON.stringify(localStorage)}`
        }
      };
  }
})();