0

So, im trying to create interactive quiz and im almost done. Only the answer checking part fails miserably. I have arrays for questions, options and the right answer, but the comparison just keeps failing.

function check(clicked_id)
{
    document.getElementById("Question").value=" " + questionArray[i];
    document.getElementById("OptionA").value=" " + aArray[i]; 
    document.getElementById("OptionB").value=" " + bArray[i]; 
    document.getElementById("OptionC").value=" " + cArray[i]; 
    document.getElementById("OptionD").value=" " + dArray[i]; 

    var selected = document.getElementById(clicked_id).value;
    var answer = answerArray[i];

    document.getElementById("text").innerHTML = answer + "<br>" + selected;

    if (selected == answer) {
        document.getElementById("comparison").innerHTML = "Correct";
    } else {
        document.getElementById("comparison").innerHTML = "Wrong";
    }   
}

And the html part is

<input onclick="check(this.id)" type="button" value="Click here to start" id="Question" /><br><br>
<input onclick="check(this.id)" type="button" value="" id="OptionA" />
<input onclick="check(this.id)" type="button" value="" id="OptionB" />
<input onclick="check(this.id)" type="button" value="" id="OptionC" />
<input onclick="check(this.id)" type="button" value="" id="OptionD" />
<div id="text"></div>
<div id="comparison"></div>

For what ever reason it just wont work and i dont understand why.

3
  • 7
    Where is i defined? Commented Apr 21, 2014 at 14:05
  • Attach a breakpoint and see if your selected and answer variables have the values you expected. Without seeing more of your code, we're just guessing. Can you put it in a fiddle? Commented Apr 21, 2014 at 14:09
  • 1
    If your test is going like showing a div for a question and after answered hide it and show another, this code will fail if you use same id for all options in each seperate divs. Commented Apr 21, 2014 at 14:12

2 Answers 2

1

You seem to be adding whitespace to the front of the value but you never remove the whitespace before you compare. At least I can't see if you do. Try this.

var selected = document.getElementById(clicked_id).value.trim();
Sign up to request clarification or add additional context in comments.

Comments

0

You should trim both the values during comparison. Something like this.

if (selected.trim() == answer.trim()) {
    document.getElementById("comparison").innerHTML = "Correct";
} else {
    document.getElementById("comparison").innerHTML = "Wrong";
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.