Skip to content
Advertisement

Comparing number always return false

I generate a random number with an interval and then I check if the number chooses by the user is the same, but it always returns false

const checkButton = document.getElementById("checkButton");
var rndNumber = RandomNumberGenerator();
checkButton.onclick = CheckNumber;
console.log("rndNumber", rndNumber);

function CheckNumber(rndNumber) {
  var numberChoosed = document.getElementById("numberChoosed").value;
  console.log("rndNumber", rndNumber)
  console.log("numberChoosed", numberChoosed);
  if (numberChoosed == rndNumber) {
    console.log("true");
  } else {
    console.log("False");
  }

}

function RandomNumberGenerator() {
  var min = document.getElementById("bottomNumber").value;
  var max = document.getElementById("topNumber").value;
  return Math.round(Math.random() * (max - min) + min);
}
<button type="button" id="checkButton">Click</button>

<input id="numberChoosed" />
<input id="bottomNumber" value="1"/>
<input id="topNumber" value="110"/>

Advertisement

Answer

Remove the rndNumber from function CheckNumber(rndNumber) { because that is actually the click event on the checkButton

Also a good idea to cast to number since .value is a string.

The == will cast for you but it is no longer up to you then

const checkButton = document.getElementById("checkButton");
var rndNumber = RandomNumberGenerator();
checkButton.onclick = CheckNumber;
console.log("rndNumber", rndNumber);

function CheckNumber() {
  var numberChoosed = document.getElementById("numberChoosed").value;
  console.log("rndNumber", rndNumber)
  console.log("numberChoosed", numberChoosed);
  console.log(+numberChoosed === +rndNumber); // cast to number

}

function RandomNumberGenerator() {
  var min = document.getElementById("bottomNumber").value;
  var max = document.getElementById("topNumber").value;
  return Math.round(Math.random() * (max - min) + min);
}
<button type="button" id="checkButton">Click</button>

<input id="numberChoosed" />
<input id="bottomNumber" value="1"/>
<input id="topNumber" value="110"/>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement