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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.