Check the right responses at the checkbox

Asked

Viewed 34 times

0

I am trying to make the message window.Alert('A checked') only appear when the three checkbox with the name="right" is marked.

HTML5

<input type="checkbox"  class="resposta" name="certo">
<label>Abrir portas para um futro promissor.</label><br>

<input type="checkbox"  class="resposta" >
<label>Ganhar dinheiro.</label><br>

<input type="checkbox"  class="resposta" name="certo">
<label>Expandir minha rede de contatos profissional.</label><br>

<input type="checkbox"  class="resposta">
<label>Diminuir o desmatamento.</label><br>

<input type="checkbox"  class="resposta" name="certo">
<label>Promover meu trabalho.</label><br>

<input type="button"  value="Verificar" onclick="verificar()">

Javascript

function verificar(){
    let resposta = document.querySelector('.resposta')
    let correto = document.getElementsByName('certo')

    for (var marcado in resposta) {
        if(resposta[marcado].checked){
            window.alert('Marcada')
            if(correto == true){
               return window.alert('A certou')
            }else{
                return window.alert('Errou')
            }
        }
        else
        return window.alert('Em branco')
    }  
}

1 answer

0


you can create a function that goes through the right input and only returns true if everyone has checked. thus:

    function verificar() {
        console.log(verificarCheckbox())
        if (verificarCheckbox()) {
            alert("Acertou")
        } else {
            alert("Errou")
        }
    }

    function verificarCheckbox() {
        let correto = document.getElementsByName('certo')
        let isValid = true
        correto.forEach(function (el) {
            if (!el.checked) {
                isValid = false
            }
        })
        return isValid
    }
  • Thanks Hiago-buzz, I hadn’t even thought to make a separate Function to go through the right input. :)

Browser other questions tagged

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