Javascript - checkbox reading value from array of objects

386 Views Asked by At

I need to get my checkboxes in todo list read from object in array if task is complete or not. And stay checked when they're complete and unchecked or not.

const todos = [
  {
    id: 1,
    title: 'Nakupit',
    description: 'Mlieko, syr, vajcia',
    completed: false,
  },
  {
    id: 2,
    title: 'Umyt auto',
    description: '+ povysavat',
    completed: true,
  },
]

This is the array and i tried on checkbox something like this. And variations, unable to get it work and changing array or value from array making checkbox ,checked, if complete

 toDoCheckbox.addEventListener('click', () => {
      if (toDoCheckbox.checked = true) {
       return todos.completed === true
        
      } else {
       return todos.completed === false
      }
    });

Can anyone help with it?

1

There are 1 best solutions below

2
Mr. Polywhirl On

You can modify the todos state by looking it up by its id and flipping its completed status.

I added the button to request re-rendering. This will re-build the checkboxes using the current state.

const todos = [{
  id: 1,
  title: 'Nakupit',
  description: 'Mlieko, syr, vajcia',
  completed: false,
}, {
  id: 2,
  title: 'Umyt auto',
  description: '+ povysavat',
  completed: true,
}]

const main = () => {
  const btn = document.querySelector('.btn-render')
  btn.addEventListener('click', reRender)
  renderTodos()
}

const reRender = (e) => {
  renderTodos()
}

const onCheck = (e) => {
  const id = parseInt(e.currentTarget.dataset.id, 10)
  const found = todos.find(todo => todo.id === id)
  if (found) {
    found.completed = !found.completed // Flip status
  }
}

const renderTodos = () => {
  const container = document.querySelector('.container')

  container.innerHTML = '' // Clear

  todos.forEach(todo => {
    let wrapper = document.createElement('div')
    let label = document.createElement('label')
    let checkbox = document.createElement('input')

    wrapper.classList.add('checkbox-wrapper')
    label.textContent = todo.title
    checkbox.type = 'checkbox'
    checkbox.checked = todo.completed
    checkbox.dataset.id = todo.id
    checkbox.addEventListener('change', onCheck)

    wrapper.appendChild(label)
    wrapper.appendChild(checkbox)
    container.appendChild(wrapper)
  })
}

main()
.checkbox-wrapper label {
  display: inline-block;
  width: 6em;
}
<div class="container"></div>
<br />
<button class="btn-render">Re-render</button>