jason jason - 1 month ago 10
HTML Question

how to pass the value of text box and compare it to the variable.. Javascript


  1. Good day! here are my codes... i hope you'd help me with this....how can i display the score when the answer is correct to or if the answer is correct?? THANK YOU IN ADVANCE :)))

  2. how can i compare the value of my textboxt to value of the results... to i can execute the if else statement>



    var points = 0;
    function setVal(){
    document.getElementById("_score").innerHTML =points;

    }

    function display(){

    var num1 = Math.round(Math.random()*10 +1);
    var num2 = Math.round(Math.random()*10 +1);

    document.getElementById("_score").innerHTML =points;

    document.getElementById('r1').innerHTML = num1;
    document.getElementById('r2').innerHTML = num2;

    var result = num1 * num2;

    var answer = document.getElementById('answer').value;

    }


    </script>


Answer

var points = 0;
var correctAnswer;

updatePoints();
init();

//Generate the 2 numbers and calculate the correct answer
function init() {
  document.getElementById("answer").value = "";

  var num1 = Math.round(Math.random() * 10 + 1);
  var num2 = Math.round(Math.random() * 10 + 1);

  document.getElementById('r1').value = num1;
  document.getElementById('r2').value = num2;

  correctAnswer = num1 * num2;
}

//Update the score
function updatePoints() {
  document.getElementById("_score").innerHTML = points;
}

//Check the user's answer with the correct one. If this is correct, score increase.
function validate() {
  var userAnswer = document.getElementById("answer").value;

  if (userAnswer == correctAnswer) {
    alert("Correct !");
    points++;
  } else {
    alert("Wrong !");
  }

  updatePoints();
  init();
}
<input type="number" id="r1" />*
<input type="number" id="r2" />=
<input type="number" id="answer" />
<button onclick="validate()">Validate</button>
<h1>Score</h1>

<p id="_score"></p>