Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda