How to convert HTML "span" + "input" elements to Number?

25 Views Asked by At

Please take a look at the code below:

  • I have created random values in JavaScript for the 3 'span' elements
  • I am gathering a response from the user via an input set to number type

However, the 'span' and 'input' values are set to NaN.

let text = "";
let num1 = document.getElementById("number1")
num1.innerHTML = Math.floor(Math.random() * (20 - 10) + 10);
let num2 = document.getElementById("number2")
num2.innerHTML = Math.floor(Math.random() * (10 - 5) + 5);
let num3 = document.getElementById("number3")
num3.innerHTML = Math.floor(Math.random() * 5) + 1;
let sum = parseInt(num1.value) + parseInt(num2.value) + parseInt(num3.value);
let yourResponse = document.getElementById("response1");
let yourNumber = parseInt(yourResponse);
let but = document.querySelector("button");
but.addEventListener("click", say)

function say() {
  if (yourNumber.value == sum) {
    text = `${yourNumber}, ${typeof yourNumber}, ${sum}, Great!`;
  } else {
    text = `${yourNumber}, ${typeof yourNumber}, ${sum}, Not quite!`
  }
  let para = document.createElement("p")
  para.textContent = text;
  document.body.appendChild(para);
  console.log(yourResponse, typeof yourResponse);
}
<div>
  <span id="number1"></span> + <span id="number2"></span> + <span id="number3"></span> = <input type="number" id="response1">
</div>

<div>
  <button type="submit" id="but">Click to submit</button>
</div>

I tried to convert the values with built-in JS functions such as parseInt() or Number(), but this did not fix the issue.

The typeof value is set to number, but the value itself is NaN.

0

There are 0 best solutions below