<html>
<body>
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()"> ok </button>
<div id = 'div'> </div>
<div id = 'div2'> </div>
<script>
var rand1, rand2, text1, text2
function button(){
text1 = document.getElementById("number").value;
// text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<input type='number' id='id'> <button onclick=' check() '> check </button> <button onclick=' again() '> again </button>" + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
var text1 = document.getElementById('number').value;
document.write(html);
}
var rand3, rand4
function again(){
rand3 = Math.floor(Math.random() * 10);
rand4 = Math.floor(Math.random() * 10);
var html1 = Number(rand3) + '+' + Number(rand4);
document.getElementById('div2').innerHTML = html1;
}
function check(){
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
document.write('<br>' + 'correct!');
} else {
document.write('<br>' + 'incorrect!');
}
}
</script>
</body>
</html>
This JS / HTML code is supposed to give me an equation like 1 + 1 and then if I click on again I get another one. But this gives me the error Untitled.html:20 Uncaught TypeError: Cannot set property 'innerHTML' of null. I have been researching this for half an hour and it says that I need to put the divs in front of the script. But I have done that and it still doesn't work. How can I fix this?
You need to close your tags. Your code can't see 'div2' because 'div' is never getting closed.
<div id='div'></div>
<div id='div2'></div>
Then, in your again
function you're calling document.write
which shouldn't be used after page load because it writes over anything you already had on the page. It is effectively removing your <div>
tags, which is then causing an error when you're trying to access them. Plus, you're already putting that value on the page through innerHTML
. Short story: remove the document.write
line in the button
function
Change <div id = 'div'>
to <div id="div"></div>
And change <div id = 'div2'>
to <div id="div2"></div>
I just checked your code, it's working fine. Try closing div tags
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.