0

I am trying to build html using ajax and after the html is built am trying to add/remove class based on a condition but the class is not getting added/removed. Can anyone please help me on this. Below is my code. showslide function is where I am trying to add/remove class

HTML -

<body class="quiz">
        <h1>Quiz on Important Facts</h1>
        <div class="quiz-container">
          <div id="quiz"></div>
        </div>
        <button id="previous">Previous Question</button>
        <button id="next">Next Question</button>
        <button id="submit">Submit Quiz</button>
        <div id="results"></div>
        </body>

Script -

$(document).ready(function(){

  var quizContainer = $('#quiz');
  var resultsContainer = $('#results');
  var submitButton = $('#submit');
  var output = [];
  var mq ='';


  function buildQuiz(){ 

      $.ajax({
        url: './json/qa.json',
        success: function(data){
          //console.log(data.myQuestions);
            mq = data.myQuestions;
            mq.forEach(
              (currentQuestion, questionNumber) => {
                const answers = [];
                for(letter in currentQuestion.answers){
                  answers.push(
                    `<label>
                      <input type="radio" name="question${questionNumber}" value="${letter}">
                      ${letter} :
                      ${currentQuestion.answers[letter]}
                    </label>`
                  );
                }
                output.push(
                  `<div class="slide">
                    <div class="question"> ${currentQuestion.question} </div>
                    <div class="answers"> ${answers.join("")} </div>
                  </div>`
                );
                quizContainer.append(output.join(''));
               // console.log("output"+output.join(''))
              });
        }

    })        
  }

  buildQuiz();

  const slides = $('#quiz').find(".slide");

  var currentSlide = 0;

  function showSlide(n) {
    console.log("slides - "+slides);
    //Here am tring to add/remove class
    $('#quiz').find('.slide').eq(0).removeClass('active-slide');
    $('#quiz').find('.slide').eq(n).addClass('active-slide');
  }

  showSlide(currentSlide);
}) 

When I do a console log of 'slides' it is returning [object object]

JSON -

{
  "myQuestions" : [
    {
      "question": "Who invented JavaScript?",
      "answers": {
        "a": "Douglas Crockford",
        "b": "Sheryl Sandberg",
        "c": "Brendan Eich"
      },
      "correctAnswer": "c"
    },
    {
      "question": "Which one of these is a JavaScript package manager?",
      "answers": {
        "a": "Node.js",
        "b": "TypeScript",
        "c": "npm"
      },
      "correctAnswer": "c"
    },
    {
      "question": "Which tool can you use to ensure code quality?",
      "answers": {
        "a": "Angular",
        "b": "jQuery",
        "c": "RequireJS",
        "d": "ESLint"
      },
      "correctAnswer": "d"
    }
  ]
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
An User
  • 221
  • 6
  • 23
  • Change the console.log(„slides „+slides) to console.log(slides). You cannot add an object to a String for Output – Thallius Jun 06 '20 at 10:20
  • @ClausBönnhoff thanks now I can see the object. Can you please help me how I can add class to nth element. When I do a console log console.log(slides.eq(0)); its returning an object. where as I need the html element so that I can add/remove class – An User Jun 06 '20 at 10:32
  • the object that is returning on console.log(slides.eq(0)) is like this - r.fn.init [prevObject: r.fn.init(0)] length: 0 – An User Jun 06 '20 at 10:45
  • I can’t see an error in your code. It should work like expected. I am on vacation with only a Tablet so it’s not so easy to reproduce. Perhaps you can make a jsfiddle? Did you check the created DOM with the browsers inspect tool if it’s build correct? – Thallius Jun 06 '20 at 11:12
  • Your issue is that you're calling `showSlide(currentSlide)` *before* the *asynchronous* ajax call has built the HTML - this should be obvious in the order of console.logs (even with `[object Object]`) - in that you get `"slides - 0"` before you get "output". There's nothing wrong with the add class https://jsfiddle.net/01bxu9fv/ - there *is* an issue that you don't clear `output` so you get the first question 3 times etc - but nothing to do with the class. – freedomn-m Jun 06 '20 at 11:26
  • Move `const slides = $('#quiz').find(".slide"); showSlide(currentSlide);` to the end of the `success:` callback (or add to a `.done`) – freedomn-m Jun 06 '20 at 11:27
  • @freedomn-m thank you very much for making it clear where the issue is. – An User Jun 06 '20 at 11:37
  • @freedomn-m I am facing difficulty in adding callback as m in training phase. Would you mind helping me with the syntax to add callback – An User Jun 06 '20 at 11:55
  • `success: function(data) { ..existing code ...; const slides = $('#quiz').find(".slide"); showSlide(currentSlide); } /* end of success:*/` – freedomn-m Jun 06 '20 at 13:21
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215449/discussion-between-an-user-and-freedomn-m). – An User Jun 07 '20 at 02:01

0 Answers0