Home > Mobile >  parseInt return NaN when take value from input box
parseInt return NaN when take value from input box

Time:04-29

i am trying to add 2 number as value from input form. typeof(parseInt(value1)) and typeof(parseInt(value2)) return number but parseInt(value1) parseInt(value2) return NaN. please someone explain

var input1 = document.getElementById('num1')
var input2 = document.getElementById('num2')
var value1 = input1.value
var value2 = input2.value
btn.addEventListener('click', myfunc)
function myfunc() {
    
    alert(typeof(parseInt(value1)))
    alert(typeof(parseInt(value2)))
    alert(parseInt(value1) parseInt(value2))
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tính toán</title>
  </head>
  <body>
    <form action="">
      <div>
        <label for="num1">Number 1</label>
        <div>
          <input type="number" name="num1" id="num1" />
          <span  id="errNum1">(*)</span>
        </div>
      </div>
      <div>
        <label for="num2">Number 2</label>
        <div>
          <input type="number" name="num2" id="num2" />
          <span  id="errNum2">(*)</span>
        </div>
      </div>
      <div></div>
      <div>
        <input type="button" value="Tính toán" id="btn" />
      </div>
    </form>
    <script src="js.js"></script>
  </body>
</html>

CodePudding user response:

You get the value of the inputs when the page is loaded, so they will always be empty. Instead you want to get the values when the button is clicked.

btn.addEventListener('click', myfunc)
function myfunc() {
    var input1 = document.getElementById('num1')
    var input2 = document.getElementById('num2')
    var value1 = input1.value
    var value2 = input2.value
    alert(typeof(parseInt(value1)))
    alert(typeof(parseInt(value2)))
    alert(parseInt(value1) parseInt(value2))
}

CodePudding user response:

The correct way to do that:

You don't need to use parseInt() on input type= number,
just use valueAsNumber property

const myForm = document.forms['my-form']

myForm.btn.onclick = evt =>
  {
  console.clear()
  console.log(typeof myForm.num1.valueAsNumber)
  console.log(typeof myForm.num2.valueAsNumber)
  console.log( myForm.num1.valueAsNumber   myForm.num2.valueAsNumber )
  }
label
, button {
  display : block;
  margin : .3em;
  }
<form action="" name='my-form'>
  <label>
    Number 1
    <input type="number" name="num1" value="0" >
  </label>
  <label>
    Number 2
    <input type="number" name="num2" value="0" >
  </label>

  <button name="btn" type="button"> Tính toán </button>

</form>

  • Related