Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!