1

I am creating a trivia game for a class and I am struggling to compare all of the values of a single index of a 2-dimensional array to a single value of a single index of another array. From my limited experience, I am using and if statement to compare these values. I must be missing a step but I am unsure how to solve it. The line of code for which I think the mistake lies is $(".choice").on('click', function() {});

Thank you for any help in advanced.

JS:

window.onload = function() {
    $('#start').html('<div class="text-center"><button type="button" class="btn btn-default">Start</button></div>');
};

var questionArray = ["This bands second album went platinum 5 times in the UK and double Platinum in the US.", "This band was formed in Australia and their first album, which had you Walking On A Dream, has sold over 3 million copies."];
var optionArray = [["Radio Head", "Gorillaz", "Coldplay", "Arctic Monkeys"], ["Empire Of The Sun", "M83", "MGMT", "Two Door Cinema Club"]];
var answerArray= ["Gorillaz", "Empire Of The Sun"];
var imageArray= ["http://cdn3.pitchfork.com/artists/1767/m.65d9c64d.jpg", "http://crowningmusic.com/storage/rA7GUFFoBCtT8Jg4L1tv.png", "", "", ""];

var count = 0;
var question = 0;

$("#start").on('click', function() {

    $(this).css("display","none");

    timer(
        30000,
        function(timeleft) { 
            $('#timer').html(timeleft);
        },
        function() { 
            // What happens after //
        }
    );

    $("#question").html(questionArray[question]);
        for (var j = 0; j < 4; j++) {
            $("#options").append('<button class="choice">' + optionArray[question][j] + "</button>" + "<br>");
        }

    $(".choice").on('click', function() {
        console.log('click');
        console.log(answerArray[question])
        if (optionArray[question] == answerArray[question]) {
            console.log("Working");
        }
    });
    // $("#holder").html("<img src=" + questionArray[count] + ">");
});

function nextQuestion() {
    count++;
}

// Timer Function //
function timer(time,update,complete) {
    var start = new Date().getTime();
    var interval = setInterval(function() {
        var now = time-(new Date().getTime()-start);
        if( now <= 0) {
            clearInterval(interval);
            complete();
        }
        else update(Math.floor(now/1000));
    },100); // the smaller this number, the more accurate the timer will be
}
4
  • 1
    What is expected result of if (optionArray[question] == answerArray[question])? Commented May 23, 2017 at 3:10
  • It looks like that line is actually comparing if an array (found at optionArray[question]) is equal to a string (found at answerArray[question]). This will always be false (unless both sides evaluate to null or undefined for some reason). You are missing the index of the selected choice. You need to get the index of the choice that was clicked, and use it like this: if (optionArray[question][choiceIndex] === answerArray[question]) Commented May 23, 2017 at 3:13
  • @pacifier21 I see what you mean...would I need to add an attr to the selected choice using $(this).attr()? and somehow take the string of the selected choice and then compare those two values? Commented May 23, 2017 at 3:17
  • Yeah - you're on the right track. See my answer below for a suggestion (doesn't mean it's the only way). You're welcome to use a different attribute (may data-...something...) if that works better for you. Commented May 23, 2017 at 3:24

2 Answers 2

1

When you are comparing the answers to the question with the correct answer, you need to include the index of the user selected choice. Try something like this:

$("#question").html(questionArray[question]);
for (var j = 0; j < 4; j++) {
    // Include an ID in the choice button
    $("#options").append('<button class="choice" id="choice_' + j + '">' + optionArray[question][j] + "</button>" + "<br>");
}

$(".choice").on('click', function() {
    console.log('click');
    console.log(answerArray[question]);

    // Get the index of the selected answer through the ID attribute
    var selectedAnswerIndex = $(this).attr('id').substring("choice_".length);
    if (optionArray[question][selectedAnswerIndex] === answerArray[question]) {
        console.log("Working");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

"I will move on to the next question if the condition does work". Why will he move to the next question only if it's correct? thats where i got confused. My Bad
@pacifier21 this is exactly what I was trying to do. adding attr is much clearer now
0

Another options that doesn't deal with answer index might look like this:

$(".choice").on('click', function() {
    console.log('click');
    console.log(answerArray[question])

    // Use the text content of the button to check the answer
    if ($(this).text() === answerArray[question]) {
        console.log("Working");
    }
});

Note: This relies on the fact that the button only contains the possible answer value between the tags. If you put anything else inside the button, this solution would not work.

2 Comments

would solution work if the next question and question options swap the html of the divs after they click either the right or wrong answer? I worked with your other solution last night and got the questions and answers to work properly while only having to add new values to the arrays. it was a great solution. have to work on the countdown timer now and should be finished after that
I think you would have to reconnect the click event callback after each question was displayed. You could pull all of that question and answer html build logic into a function, and call that function when you're ready for the next question. You would of course need to increment the question index (question++) before building the next question and answer html elements. I hope that all made sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.