mercredi 9 mars 2022

How to change already checked (by default) checkbox's status and keep it unchecked?

I have multiple checkboxes with checked attribute in it. I want them to be checked by default. I also store selection in locakStorage when move to next page. However, if I want to unselect some of the checkboxes and move back forward and go back to previous page, all checkboxes looks still checked, even if in localStorage unchecked ones are not stored. You can see my code below. I am stuck, so please don't find my question stupid and unvote it. I really appreciate for any help.

<input type="checkbox" name = "group3" id="opt1" value="o1" checked>
<label for="opt1">Option 1</label>

<input type="checkbox" name = "group3" id="opt2" value="o2" checked>
<label for="opt2">Option 2</label>
function storeSelection() { 
    var array = []
    const checkboxes = document.querySelectorAll('input[name=group3]:checked')
    for (let i = 0; i < checkboxes.length; i++) {
        array.push(checkboxes[i].value)
    }
    localStorage.setItem("checkbox", JSON.stringify(array))

unChecked = document.querySelectorAll('input[name=group3]:not(:checked)')
checked = JSON.parse(localStorage.getItem("checkbox"))
for (let i = 0; i < unChecked.length; i++) {
    if(checked.includes(unChecked[i].value) == true){
        unChecked[i].checked = true;
    }
}



Aucun commentaire:

Enregistrer un commentaire