I want to make something like:
1. 1296
2. 4624
Square root both numbers and add the result!
Answer: ________
[Check button]
and open the somewhere.html if the answer is correct
I made this script:
<html>
<head>
<script language="javascript">
window.onload=calc;
function calc() {
var num1, num2, sqNum1, sqNum2, randomNum, sum, ans;
num1=Math.floor(Math.random()*90)+10;
num2=Math.floor(Math.random()*90)+10;
sqNum1=num1*num1;
sqNum2=num2*num2;
sum=num1+num2;
document.write("1. " + sqNum1 + "<br />");
document.write("2. " + sqNum2 + "<br />");
document.write("<br />");
}
function checkAns(form) {
if (form.ans.value==sum) {
location="somewhere.html";
} else {
alert ("Wrong answer!");
}
}
</script>
</head>
<body>
Square root both numbers and add the result! <br />
<form name='question'>
Answer: <input name='ans' type='password'> <br />
<input type='button' value='Check' onClick='checkAns(this.form)'>
</form>
</body>
</html>
Whatever I tried, it never displays this part:
Square root both numbers and add the result!
Answer: ________
[Check button]
What is wrong with this script?
2 Answers 2
By the time the load function is called, the document it in a closed state.
You cannot write to a document in a closed state, so calling write will call open for you.
Calling open will wipe out the existing document.
The new content is written to the new document.
Use DOM manipulation (createElement, appendChild and friends) to edit an existing document.
Comments
You need something like this:
<html>
<head>
<script language="javascript">
function calc() {
var num1, num2, sqNum1, sqNum2, randomNum, sum, ans;
num1=Math.floor(Math.random()*90)+10;
num2=Math.floor(Math.random()*90)+10;
sqNum1=num1*num1;
sqNum2=num2*num2;
sum=num1+num2;
document.getElementById("sum").value = sum;
var question = document.getElementById("question");
var numbers = document.getElementById("numbers");
var br = document.createElement('br');
var txt = document.createTextNode("1. " + sqNum1);
numbers.appendChild(txt);
numbers.appendChild(br);
var txt = document.createTextNode("2. " + sqNum2);
numbers.appendChild(txt);
txt.appendChild(question);
}
function checkAns(form) {
if (document.getElementById("ans").value == document.getElementById("sum").value) {
var newWin = open('somewhere.html','windowName','height=300,width=300');
} else {
alert ("Wrong answer!");
}
}
</script>
</head>
<body onload="calc();">
<form name='question'>
<div id="numbers">
</div>
<br/>
Square root both numbers and add the result! <br />
<div id="question">
Answer: <input id='ans' name='ans' type='password'> <br />
<input type='button' value='Check' onClick='checkAns(this.form)'>
</div>
<input id='sum' type='hidden' value=''/>
</form>
</body>
</html>
This is not the best answer, it is one way you can use to follow with your development
suminside of thecalcfunction. When declaring a variable withvarinside of a function, its scope is limited to inside of that function. Read here to learn more about scope in JavaScript.