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')
?– Sam
Function selects(x){ Return Document.getElementById(x); };
– Amauri Santos
Amauri, put the html code too.
– André Lins
I edited to try to clarify my doubt
– Amauri Santos