Javascript - Checkbox and Local Storage. If there are matching values, then check the checkbox

Viewed 446

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();
2 Answers

You have to set a default value (an empty array) for storage if no item is saved.

const storage = JSON.parse(localStorage.getItem('cart')) || [];

Then change your checkInputs to

const checkInputs = () => {
    inputs.forEach((input) => {
        // check input if name in storage
        input.checked = storage.some((item) => item.name === input.value);
    })
}

I use some method, to check if name is in storage.

You just need to change this line, you are comparing instead assign.

exist ? input.checked = true : input.checked = false;

const checkInputs = () => {
  inputs.forEach((input) => {
    // check if localStorage has matching values with existing input values.
    const exist = storage.find((item) => item.name === input.value);
    console.log(exist)
    // if exist returns true, then check that input box, otherwise leave box unchecked;
    exist ? input.checked = true : input.checked = false;
  })
}

Related