Home  >  Q&A  >  body text

How can I change the selected checkboxes (select all) after unchecking one of the following checkboxes?

I just created the check all script in JS but don't know how to implement it to check if all my checkboxes are still checked and if not - uncheck my "select all" checkbox. Any ideas on how to do this?

This is my code, please take a look, pure JS

function toggle() {
    let selector = document.querySelector('.chbx_selector');
    let selection = document.querySelectorAll('.chbx_selection');

    selector.addEventListener('click', () => {
        if (selector.checked === true) {
            selectAll(selection)
        }
        else {
            deselectAll(selection)
        }

    });
}

function selectAll (selection) {
    selection.forEach(chbx => {
        chbx.checked = true;
    });
}

function deselectAll (selection) {
    selection.forEach(chbx => {
        chbx.checked = false;
    });
}

toggle()

I seem to have exhausted my mental capacity to solve the problem, although I'm still trying to do something with the eventListener click type in hopes of achieving the desired result. Any help is appreciated.

P粉463418483P粉463418483182 days ago428

reply all(1)I'll reply

  • P粉642920522

    P粉6429205222024-04-02 15:41:11

    You can set event listeners on non-selected checkboxes. In this event you can check the checked state of the checkbox and if it is not checked then update the checkbox to uncheck it.

    This way, all your checkboxes will stay in sync as long as any other checkbox is unchecked.

    reply
    0
  • Cancelreply