Javascript

i am using javascript prompt function and document.write but can not make the document.write commands execute prior to the prompt commands.

The prompt commands execute first and then the document.write commands are then executed.

However the lines of code call the document.write commands first.

My code is basic and listed below:
quiz.htm

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <script src="quiz.js"></script>
  <title>The Ultimate Quiz Challenge</title>
 </head>
<body  onload="askQuestions();">
  <div class="container">
  <h1>The Ultimate Quiz Challenge</h1>
  <h3>Welcome to the ultimate quiz challenge</h3>
  <p>I am going to asking a number of questions and rate your performance</p>
</div>
<div id="questions">
</div>  
</body>
</html>

quiz.js

function askQuestions()
{
  var question1 ="<p>What is the capital of England</p>";
  var firstanswer ="London";
  var question2 = "<p>How many sides are there to a square</p>";
  var secondanswer = 4;
  var noofquestions = 2;
  var count = 1
    while (count <= 2) {
        var temp = eval('question' + count);
       /* document.getElementById("questions").innerHTML += temp; */
          document.write(temp);
        var answer = prompt("Please type your answer ");
        count++;
    }
}

Avoid using document.write. Your first method of getElementById was correct. Just set it to = instead of +=.

document.getElementById("questions").innerHTML = temp;

The reason it probably didn’t work is because your script is running before the DOM element #questions exists. Try moving the script to the bottom and then immediately running it instead of using onLoad.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>The Ultimate Quiz Challenge</title>
 </head>
<body>
  <div class="container">
  <h1>The Ultimate Quiz Challenge</h1>
  <h3>Welcome to the ultimate quiz challenge</h3>
  <p>I am going to asking a number of questions and rate your performance</p>
</div>
<div id="questions">
</div>
<script src="quiz.js"></script>
<script>askQuestions();</script>
</body>
</html>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.