2

I'm building a really simple quiz: http://fh80.student.eda.kent.ac.uk/fyp-assets/quiz/quiz.php

At the end of the quiz it should display how many you got right e.g 5/10.

One thing about it is that each question is pulled in via AJAX so every question is a different .php file. Also, for every question there is the question page and an answer page. E.g question1.php and question1a.php

I've created a variable on the page for the score:

/* Quiz Score */
var quizScore = 0;

When you load up question1.php through AJAX, there is this script:

document.getElementById("nextQuestion1a").onclick = function(){
var correctAnswer = document.getElementById("lightningbolt");
if (correctAnswer.checked){
    quizScore = quizScore+1;
}else{}};

The correct answer has an ID of lightningbolt

<input type="radio" name="question1" value="lightningbolt" id="lightningbolt">Lightning Bolt<br>

So, when this input/radio button is checked it should follow the function and +1 to quizScore;

if (correctAnswer.checked){
    quizScore = quizScore+1;

I think this isn't working, because the event handler for doing this is onClick of nextQuestion(ID) - this is the same button which launches the AJAX which takes you to the next page (in this case, clicking nextQuestion1a takes you to question1a.php)

So I am thinking I need to bind it different somehow. Like not on click of that button, but just on check of the radio button.

At the end of the quiz I output the score as such:

<h3>
    You got 
    <script>document.write(quizScore);</script>
    /10
</h3>

But this doesn't output any value, not even 0 as the variable was initialised.

ETA: the variable does exist on the page at all times. The variable is not declared within the refreshed content. So the variable is always there.

Francesca
  • 26,842
  • 28
  • 90
  • 153
  • 1
    Why are you using document.write? That is a bad idea – epascarello Mar 14 '14 at 17:07
  • @epascarello Can you please suggest an alternative then. – Francesca Mar 14 '14 at 17:07
  • *same button which launches the AJAX which takes you to the next page*: There's your problem. This isn't AJAX, you are just loading another page. Javascript variables only exist for the lifetime of the page you are on. If you intended to actually use AJAX, you should load the content and append it to the current page. – Matt Burland Mar 14 '14 at 17:09
  • @MattBurland it is the same page. It uses AJAX. It doesn't completely refresh the page, only part of it. And the variable exists outside of that refreshed content. I thought this might be an issue but figured because the variable is always there throughout any AJAX refreshes it was OK. – Francesca Mar 14 '14 at 17:13
  • Use `createElement` and `appendChild` instead of `document.write`. And also don't inline script tags in your HTML in the first place. It's a horrible practice. – Matt Burland Mar 14 '14 at 17:13

0 Answers0