const key = "checklist-items"; const objs = JSON.parse(window.localStorage.getItem(key) || "{}"); let currentId = Math.max(Object.keys(objs)) || 0; const save = () => { window.localStorage.setItem(key, JSON.stringify(objs)); }; const updateChecklistItem = (id, name, done) => { objs[id] = { name, done }; }; const deleteChecklistItem = (id) => { delete objs[id]; save(); }; const onChange = () => { save(); render(); }; const render = () => { const checklistEl = document.getElementById("checklist"); checklistEl.innerHTML = ""; Object.keys(objs).forEach(id => { const { name, done } = objs[id]; const inputGroup = document.createElement('div'); inputGroup.className = 'input-group mb-3'; /* Prepend (for the checkbox) */ const inputPrepend = document.createElement('div'); inputPrepend.className = 'input-group-prepend'; const inputPrependGroupText = document.createElement('div'); inputPrependGroupText.className = 'input-group-text'; /* Checkbox and input together so they can read each other's vals on change */ const checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.ariaLabel = "Checkbox for following text input"; checkbox.checked = done; inputPrependGroupText.appendChild(checkbox); inputPrepend.appendChild(inputPrependGroupText); const input = document.createElement('input'); input.type = "text"; input.className = "form-control"; input.ariaLabel = "Text input with checkbox"; input.value = name; input.style.textDecoration = done ? 'line-through' : 'none'; input.id = `${id}-${name}`; input.addEventListener('input', _ => { updateChecklistItem(id, input.value, checkbox.checked); save(); }); checkbox.addEventListener('change', _ => { updateChecklistItem(id, input.value, checkbox.checked); if (checkbox.checked) { input.style.textDecoration = 'line-through'; } else { input.style.textDecoration = 'none'; } save(); }); /* The delete button */ const inputGroupAppend = document.createElement('div'); inputGroupAppend.className = 'input-group-append'; const btn = document.createElement('button'); btn.className = "btn btn-danger"; btn.type = 'button'; btn.addEventListener('click', _ => { deleteChecklistItem(id); onChange(); }); btn.innerHTML = ` `; inputGroupAppend.appendChild(btn); inputGroup.appendChild(inputPrepend); inputGroup.appendChild(input); inputGroup.appendChild(inputGroupAppend); checklistEl.appendChild(inputGroup); }); }; const load = () => { document.getElementById('form').addEventListener('submit', evt => { evt.preventDefault(); evt.stopPropagation(); currentId = currentId + 1; objs[currentId] = { name: document.getElementById('new-item-name').value, done: document.getElementById('new-item-done').checked }; onChange(); document.getElementById('new-item-name').value = ''; document.getElementById('new-item-done').checked = false; }); render(); }; window.addEventListener('load', load);