-1

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 Answers1

0

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Mr. Polywhirl , i got it working like this. But it doesn't work other way around. I need to change array value when clicking checkbox. Not render checkbox after value i change in the array – Miroslav Valkovič Jul 20 '20 at 12:10
  • @MiroslavValkovič This does change the status of the array values... See: `found.completed = !found.completed` – Mr. Polywhirl Jul 20 '20 at 12:30