How to enter checkbox validation logic and display message if not selected

Asked

Viewed 242 times

0

Currently, in my quiz, the user can proceed to the next question without at least selecting an answer option.

I am trying to put a condition where If an option is not selected, display an alert message and at the same time disable the button to proceed.

First I finished the quiz without trying to validate the inputs. HTML code:

<section class="nivelamento" id="nivelamento">
    <div class="container">
        <h2 id='teste_status' class="nivelamento-titulo">English Questions!</h2>
        
        <h6 id="progresso">Question</h6>
        <div id="teste">

            
        </div>    
    </div>
</section>

My js file:

function seleciona(x){
    return document.getElementById(x);
};

function criaQuestao() {
    var myDiv = seleciona('teste');
    var h6 = seleciona('progresso');

    if(pos >= quizArray.length){
        myDiv.innerHTML = "<h2>Você acertou " + correto + ' de ' + quizArray.length + " questões</h2>"
        myDiv.innerHTML +=  "<button onClick='document.location.reload(true)' class='btn btn-danger btn-sm'>Refazer</button>";
        pos = 0;
        correto = 0;
        return false;
    }

    h6.innerHTML = 'Questão ' + (pos + 1) + ' de ' + quizArray.length;
   
    pergunta = quizArray[pos].question;
    op1      = quizArray[pos].opcao1;
    op2      = quizArray[pos].opcao2;   
    op3      = quizArray[pos].opcao3; 
        
    myDiv.innerHTML = "<h2>" + pergunta + "</h2><br>";
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='A'> " + op1 + "<br>";
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='B'> " + op2 + '<br>';
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='C'> " + op3 + '<br><br>';
    myDiv.innerHTML +=  "<button onclick='verificaResposta()' class='btn btn-danger btn-sm'>Submit Answer</button>";


};

function verificaResposta(){
    var opcoes = document.getElementsByName('opcoes');
    for(var i = 0; i < opcoes.length; i++){
        if(opcoes[i].checked){
            opcoes = opcoes[i].value;
        } 
    }

    if(opcoes === quizArray[pos].resposta){
        correto++;
    }

    pos++;
    criaQuestao();
};

window.addEventListener('load', criaQuestao, false);

Then I tried to implement the validation logic still in the same function:

function verificaResposta(){
    var opcoes = document.getElementsByName('opcoes');
    var button = document.querySelector(".clicado");
    var botao_clicado = false;
    button.addEventListener('click', ()=>{
        for(var i = 0; i < opcoes.length; i++){
            if(opcoes[i].checked){
                opcoes = opcoes[i].value;
                botao_clicado= true;
            }if(!botao_clicado){
                var myDiv = seleciona('teste');
                myDiv.innerHTML = '<h4>Selecione uma resposta<h4>'
            }
        }
    })   

    if(opcoes === quizArray[pos].resposta){
        correto++;
    }

    pos++;
    criaQuestao();
};

But after I execute nothing happens. Can anyone tell me why my validation logic isn’t working?

  • What would that be: seleciona('teste')?

  • Function selects(x){ Return Document.getElementById(x); };

  • Amauri, put the html code too.

  • I edited to try to clarify my doubt

1 answer

2


You are not using checkboxes, and yes radio Buttons.

There are several structural and logic problems in the code. The most serious is that you are using the div#teste to replace the message "Select an answer" and the question itself.

Other problems is that you use the same variable opcoes array to check the checked option, causing value change in opcoes.length in the loop for:

opcoes = opcoes[i].value;

Another is that you’re putting one button.addEventListener('click', ()=>{ within the function that is already called by an event click on onclick='verificaResposta()'.

That one Event Handler .addEventListener('click'... should hear the radio Buttons so that when one is checked, rehabilitate the button, and at the end of the function criaQuestao(), because those addEventListener should be recreated by inserting a new question.

See how your code should work:

// array só para exemplo
quizArray = [
   {
      question: 'Pergunta 1',
      opcao1: 'A',
      opcao2: 'B',
      opcao3: 'C',
      resposta: 'B'
   },
   {
      question: 'Pergunta 2',
      opcao1: 'A',
      opcao2: 'B',
      opcao3: 'C',
      resposta: 'C'
   }
];


var pos = 0;
var correto = 0;

function criaQuestao() {
    var myDiv = seleciona('teste');
    var h6 = seleciona('progresso');

    if(pos >= quizArray.length){
        myDiv.innerHTML = "<h2>Você acertou " + correto + ' de ' + quizArray.length + " questões</h2>"
        myDiv.innerHTML +=  "<button onClick='document.location.reload(true)' class='btn btn-danger btn-sm'>Refazer</button>";
        pos = 0;
        correto = 0;
        return false;
    }

    h6.innerHTML = 'Questão ' + (pos + 1) + ' de ' + quizArray.length;
   
    pergunta = quizArray[pos].question;
    op1      = quizArray[pos].opcao1;
    op2      = quizArray[pos].opcao2;   
    op3      = quizArray[pos].opcao3; 
        
    myDiv.innerHTML = "<h2>" + pergunta + "</h2><br>";
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='A'> " + op1 + "<br>";
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='B'> " + op2 + '<br>';
    myDiv.innerHTML += "<input type='radio' name='opcoes' value='C'> " + op3 + '<br><br>';
    myDiv.innerHTML +=  "<button onclick='verificaResposta()' class='btn btn-danger btn-sm'>Submit Answer</button>";

   var opcoes = document.getElementsByName('opcoes');
   for(var i = 0; i < opcoes.length; i++){
      opcoes[i].addEventListener('click', ()=>{
         document.querySelector("#teste button").disabled = false;
      });
   }

};

function seleciona(x){ return document.getElementById(x); }


function verificaResposta(){
    var opcoes = document.getElementsByName('opcoes');
    var botao_clicado = false;
    var opcao;
     for(var i = 0; i < opcoes.length; i++){
         if(opcoes[i].checked){
             opcao = opcoes[i].value;
             botao_clicado= true;
         }
     }

      var myDiv = seleciona('teste');
      if(!botao_clicado && !myDiv.querySelector("h4")){
         var no = document.createElement("h4");
         var txt = document.createTextNode("Selecione uma resposta");
         no.appendChild(txt);
         myDiv.appendChild(no);
         document.querySelector("#teste button").disabled = true;
         return;
      }

    if(opcao === quizArray[pos].resposta){
        correto++;
    }

   if(botao_clicado){
       pos++;
       criaQuestao();
   }
};

document.addEventListener("DOMContentLoaded", criaQuestao, false);
<section class="nivelamento" id="nivelamento">
    <div class="container">
        <h2 id='teste_status' class="nivelamento-titulo">English Questions!</h2>
        
        <h6 id="progresso">Question</h6>
        <div id="teste">

            
        </div>    
    </div>
</section>

  • It worked! Show. I only had to put Document.addeventlistener("Domcontentloaded", createQuestao, false); at the top of the page. At the end it doesn’t work

Browser other questions tagged

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