JavaScript
x
17
17
1
function button(){
2
text1 = 4
3
var rand1 = Math.floor(Math.random() * text1);
4
var rand2 = Math.floor(Math.random() * text1);
5
var answer1 = rand1 + '+' + rand2;
6
var html = rand2 + '+' + rand1
7
document.write(html)
8
}
9
function check(rand1, rand2){
10
var text11 = document.getElementById('id').value;
11
var answer = rand1 + rand2;
12
if(answer == text11) {
13
document.write('correct!')
14
}
15
}
16
17
button()
JavaScript
1
2
1
<input type="text" id="id">
2
<button onclick="check()"> check </button>
I want my code to create simple equations. You can put in answers and it tells you if you are correct or not. When I run this simple code, input the right answer and click on check, it doesn’t show correct. why is this and how can I fix?
Advertisement
Answer
In your code, check()
requires two arguments rand1
and rand2
, which you are not passing while calling it from onclcik
.
Following code should work, check it…
JavaScript
1
25
25
1
<html>
2
<body>
3
4
<script>
5
function button(){
6
text1 = 4
7
var rand1 = Math.floor(Math.random() * text1);
8
var rand2 = Math.floor(Math.random() * text1);
9
var answer1 = rand1 + '+' + rand2;
10
var html = rand2 + '+' + rand1
11
document.write(html)
12
return rand1 + rand2;
13
}
14
function check(){
15
var text11 = document.getElementById('id').value;
16
if(answer == text11) {
17
document.write('correct!')
18
}
19
}
20
var answer = button()
21
</script>
22
<input type="text" id="id">
23
<button onclick="check()"> check </button>
24
</body>
25
</html>