Dynamically Checking Checkboxes with Array of Booleans

I have an array that starts out empty

let checkboxArray = [];

I also have a table that contains a column of checkboxes with the class eztext

Every time a checkbox is clicked an event handler fires that empties the array and updates it with all of the checkbox.checked values.

const checkboxes = document.querySelectorAll('.eztext');

checkboxes.forEach((checkbox) => {
    checkbox.addEventListener('click', function () {
        checkboxArray = [];
        checkbox.forEach((checkbox) => {
            checkboxArray.push(checkbox.checked);
        });
    });
});

What I’d like to happen now is when a function called init() is run, I’d like to update all of the checkboxes with the boolean values from the checkboxArray. However, when I run this function and any variation I’ve tried, they all get checked.

function init() {
    const checkboxes = document.querySelectorAll('.eztext');

    if (checkboxArray.length > 0) {
        checkboxes.forEach((checkbox, i) => {
            const isChecked = checkboxArray[i].toString();
            checkbox.setAttribute('checked', isChecked);
        });
    } 
}

Thanks for the help!

Hello!

The problem is that a checkbox gets checked whenever the attribute is present, irrespective of the value:

<label>Just checked <input type="checkbox" checked /></label>
<label>Checked true <input type="checkbox" checked="true" /></label>
<label>Checked false <input type="checkbox" checked="false" /></label>
<label>No attribute <input type="checkbox" /></label>

Building on @skaparate, maybe to solve this you could add a check to init() like…

const isChecked = checkboxArray[i].toString();
if (isChecked === 'true') {
 checkbox.setAttribute('checked' , isChecked);
}

Tell us how it works out :slight_smile:

Hey! Thanks for the help, I’ve gotten it sorted. I sort of created a hybrid of your solution @Erma32. Checkboxes seem to always give me issues! So what I did was remove the checked style for each checkbox then conditionally add it back depending on the value stored in the array.

function init () {
    const checkboxes = document.querySelectorAll('.eztext');

    if (checkboxArray.length > 0) {
        checkboxes.forEach((checkbox, i) => {
            checkbox.removeAttribute('checked');
            const isChecked = checkboxArray[i];
            if (isChecked) {
                checkbox.setAttribute('checked', '');
            }
        }
    }
}