Check addition of two random numbers using javascript

With below Javascript code you can easily create random numbers and check addition of that two random numbers by use entered input.


<!DOCTYPE html>

<html>

<head>

    
    <title>Play Game using JavaScript</title>

    

</head>

<body>

<table width="400" border="1" align="center">

  <tr>

    <td><div id="number1">1</div></td>

    <td><div>+</div></td>

    <td><div id="number2">2</div></td>

    <td><div>=</div></td>

    <td><input type="text"></input></td>

    <td><input type="button" value="Check"></input></td>


  </tr>

</table>

<script>

    //random number appear when start game

        var number1;

        var number2;

        
        number1 = Math.floor((Math.random() * 10) + 1);

        number2 = Math.floor((Math.random() * 10) + 1);

        document.getElementById("number1").innerHTML=number1;

        document.getElementById("number2").innerHTML=number2;

        
        //Answer

        var answer = number1 + number2;

        
        //add click handler with check answer

        var checkAnswer = document.querySelector('input[type=text]');

        var value = checkAnswer.value;

        var btn = document.querySelector('input[type=button][value=Check]');

        
        
        btn.onclick = function() 

        {

          if (checkAnswer.value == answer)


               {

                  alert('You are correct');

               }

           else{

                  alert('You are incorrect, the answer was ' + answer);

               }

        
         document.querySelector('input[type=text]').value = "";               

         document.getElementById('number1').innerHTML = "";

         document.getElementById('number2').innerHTML = ""; 

         number1 = Math.floor((Math.random() * 10) + 1);

         number2 = Math.floor((Math.random() * 10) + 1);

         document.getElementById('number1').innerHTML = number1; 

         document.getElementById('number2').innerHTML = number2;

        
         answer = number1 + number2

        
        
        };

    </script>

</body>

</html>

Post a Comment

0 Comments