0

I have created a simple quiz in an HTML-document, and I want to display the score in another HTML-document. How do I place a variable from a script file to an element in an HTML file?

This is my Javascript code, with most of the if-statemnts edited out (they are all the same):

var score = 0;

function start(){
    if (document.getElementById('radio13').checked){
        score ++;
    }
    if (document.getElementById('radio23').checked){
        score ++;
    }
    var finalscore = score *10;
    var results = "Your score is: " + finalscore + " %.";
    window.location.replace("quizresults.html");
    document.getElementById('presult').innerHTML = results;
}

The new page loades, but it is empty. This is the HTML-code for the result-page where I wish to add the score:

<div id="main">
        <p id="presult"></p>
</div>
2
  • 2
    You can only modify the current document via JavaScript. You could pass the value via the URL and read the value from URL with JavaScript in quizresults.html. Commented Dec 15, 2014 at 23:30
  • 1
    You can use cookies to pass values between pages. Commented Dec 15, 2014 at 23:31

2 Answers 2

1

by using window.location.replace you're pointing your browser to a new, different page. As such, the last line of your code will not be executed.

To achieve your goal, use XMLHttpRequest

Sign up to request clarification or add additional context in comments.

Comments

0

Here's how you can do it using a JavaScript query string.

On your page with the radio buttons, use this:

var score = 0;

function start(){
    if (document.getElementById('radio13').checked){
        score ++;
    }
    if (document.getElementById('radio23').checked){
        score ++;
    }
    var finalscore = score *10;
    var results = "Your score is: " + finalscore + " %.";
    window.location.replace("quizresults.html?" + finalscore);
}

Then you need this JavaScript code on the result page:

var finalscore = window.location.search.slice(1);
var results = "Your score is: " + finalscore + " %.";
document.getElementById('presult').innerHTML = results;

2 Comments

That worked. I had to try it a few times, but once I plased it in the <body>, beneath 'presult' it worked just fine.
Good. I'm glad I could help.

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.