Skip to content
Advertisement

random equations in javascript

  function button(){
    text1 = 4
    var rand1 = Math.floor(Math.random() * text1);
    var rand2 = Math.floor(Math.random() * text1);
    var answer1 = rand1 + '+' + rand2;
    var html = rand2 + '+' + rand1
    document.write(html)
  }
  function check(rand1, rand2){
    var text11 = document.getElementById('id').value;
    var answer = rand1 + rand2;
    if(answer == text11) {
      document.write('correct!')
    }
  }
  
  button()
<input type="text" id="id">
<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…

<html>
<body>

<script>
  function button(){
    text1 = 4
    var rand1 = Math.floor(Math.random() * text1);
    var rand2 = Math.floor(Math.random() * text1);
    var answer1 = rand1 + '+' + rand2;
    var html = rand2 + '+' + rand1
    document.write(html)
    return rand1 + rand2;
  }
  function check(){
    var text11 = document.getElementById('id').value;
    if(answer == text11) {
      document.write('correct!')
    }
  }
  var answer = button()
</script>
<input type="text" id="id">
<button onclick="check()"> check </button>
</body>
</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement