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

120
Views
JQuery: How to simplify classes selection with serial number in event delegation

I create web quiz with each question and option element dynamically generated according to an array.

Below is my script:

function showQuestion(){
    for(let i = 0; i < QuesPartA.length; i++){
        $(".questionBox").append('<div class="Question">Number '+ parseInt(i+1) +'</div>');
        $(".questionBox").append('<div class="Options" id="optId'+ parseInt(i+1) +'">');
        QuesPartA[i]['option'].forEach(option => {
            $("#optId"+ parseInt(i+1)).append('<span class ="pilihan'+ parseInt(i+1) +'">'+option +' </span><br>');  
        });
        $(".questionBox").append('</div><br>'); // end Options div
    } 
    $(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>'); 
};



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

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

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

};

The first function is to show the question and answer. The second is to give color to each option when user clicks.

However, the second function is going to be very long since the quiz consists of 30 questions. Is there any ways to do that simpler so that I don't need to write 30 event delegations?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use set an ID to each button

QuesPartA[i]['option'].forEach(option => {
        $("#optId"+ parseInt(i+1)).append('<span id = "'pilihan'+parseInt(i+1)+'" class ="pilihan'+ parseInt(i+1) +'">'+option +' </span><br>');  
    });

and use this syntax to add an event to all buttons

function changeColor(){
  $(".questionBox").on("click",'[id^=pilihan]', function() {
    $(this).css("background", "red");
    ...
  });
about 4 years ago · Juan Pablo Isaza Report

0

In general terms, it's best to completely avoid incremental id and class attributes in repeated blocks of content, and instead relate them to each other using DOM traversal methods within the relevant event handlers.

In this case, given the implied HTML structure, you can give all the clickable span elements the same class and then find() them within the closest() parent question div.

Also note that the logic can be made more succinct by using map() to build the HTML. Try this:

let QuesPartA = [{
  option: [ 'Foo', 'Bar', 'Fizz', 'Buzz' ]
}];


function showQuestion() {
  let questionHtml = QuesPartA.map((question, i) => {
    let optionHtml = question.option.map(opt => `<span class="pilihan">${opt}</span><br />`).join('');
    return `<div class="Question">Number ${i + 1}</div><div class="Options">${optionHtml}</div><br />`;
  }).join(''); 
  
  $(".questionBox").append(questionHtml);
  $(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
};

function changeColor() {
  $(".questionBox").on("click", ".pilihan", e => {
    let $opt = $(e.target);
    $opt.closest('.Options').find('.pilihan').removeClass('active');
    $opt.addClass('active');
  });
};

showQuestion();
changeColor();
.pilihan { color: #CCC; }
.pilihan.active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="questionBox"></div>
<div class="secondBox"></div>

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!