How to check if at least one checkbox is enabled

Asked

Viewed 144 times

-4

I have a set of checkboxes and I need a javascript function that, when submitting the form, check if at least one is checked and display the alert to select if it is not. I can’t use radio in this case, it has to be checkboxes.

<input type="checkbox" name="opção1" value="true" />
<input type="checkbox" name="opção2" value="true" />
<input type="checkbox" name="opção3" value="true" />
<input type="checkbox" name="opção4" value="true" />
<input type="submit" value="ENVIAR" />

2 answers

1


There are some ways to do that. In the code below I put a class check in all checkboxes to make it easier to pick up all the elements with javascript, it tests one by one to see if it is tight and if it is not tight, it presses the first.

HTML

    <input type="checkbox" class="check" name="opção1" value="true"/>
    <input type="checkbox" class="check" name="opção1" value="true"/>
    <input type="checkbox" class="check" name="opção1" value="true"/>
    <input type="checkbox" class="check" name="opção1" value="true"/>

Javascript

    checkBoxes = document.getElementsByClassName("check")
    noCheckedBoxes = true
    for (i = 0; i< checkBoxes.length; ++i) {
        if(checkBoxes[i].checked) {
            noCheckedBoxes = false
        }
    }
    if(noCheckedBoxes) {
        checkBoxes[0].checked = true
    }

0

another more "lean" way would be using foreach in a querySelectorAll to check all inputs of checkbox type:

let noCheckedBox = false;
document.querySelectorAll("input[type=checkbox]").forEach(e=> {
    if (!e.checked) noCheckedBox = true;
});
if (noCheckedBox) alert("Nenhum checkbox selecionado!");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.