I have a form, that when submitted, pushes the checked boxes into localStorage.
Upon return or refresh, I'd like to have boxes that has matching values with localStorage to be checked. I have some conditional in my Javascript below, located where my comments are. Is that the right conditional for this?
Also if there are better ways to do this, please do share. I'm actually going to be doing this with React and Redux Thunk. But just wanted to give this a try with vanilla JS.
HTML
<form onsubmit='setStorage()'>
<input type='checkbox' value='toy'/> Toy
<input type='checkbox' value='bag'/> Bag
<input type='checkbox' value='cup'/> Cup
<input type='submit' value='Submit'>
</form>
<ul class='cart'>
</ul>
Javascript
const storage = JSON.parse(localStorage.getItem('cart'));
const inputs = document.querySelectorAll('input');
const checkInputs = () => {
inputs.forEach((input) => {
// check if localStorage has matching values with existing input values.
const exist = storage.find((item) => item.name === input.value);
// if exist returns true, then check that input box, otherwise leave box unchecked;
exist ? input.checked === true : input.checked === false;
})
}
const setStorage = () => {
const updatedStorage = [];
inputs.forEach((input) => {
input.checked ? updatedStorage.push({name: input.value}) : null;
})
localStorage.setItem('cart', JSON.stringify(updatedStorage));
}
const setCart = () => {
const cart = document.querySelector('.cart');
storage.forEach((item) => {
const li = document.createElement('li');
const name = document.createElement('p');
name.innerText = item.name;
cart.append(li);
li.append(name);
})
}
checkInputs();
setCart();