Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
Building quiz in Javascript: Select only one of dynamic elements plus the ability to change choice

I try to build a quiz of 30 questions with dynamically generated elements.

The html:

  <div class="secondBox">
           <div class="questionBox">
           </div>
            
  </div>

Here's my script:


function showQuestion(){
    for(let i = 0; i < QuesPartA.length; i++){
      $(".questionBox").append('<div class="Question">Number '+ parseInt(i+1) +'</div>');
      QuesPartA[i]['option'].forEach(option => {
          $(".questionBox").append('<span class="pilihan">'+option +' </span><br>');  
      });
     
  } 

$(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
  };

$(".questionBox").on("click", ".pilihan", function() {
  $(this).css("background", "red");
  $('.pilihan').not(this).css("background", "#ccc");

So the dynamically generated element will show 30 questions with four answer options each. I want to change the color of the option to be red once the user clicks, plus with the ability to change choice.

I can do that with the code above: I can choose an answer for question number 1 (one of the options change to red), but when I click an answer for number 2, the chosen option in question 1 goes back to #ccc color. It goes the same way when I choose an option in question 3, the chosen answers for number 2 and 1 go back to #ccc.

Does anyone have any ideas so that everytime I click an answer for the next question the previous ones remain red?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I believe that the .not() always fails in this line:

$('.pilihan').not(this).css("background", "#ccc");

Which results in the background being changed to #ccc.

Try just removing that whole line...

$('.pilihan').not(this).css("background", "#ccc");

This should also cause any line that was turned red to remain red.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda