HTML input type="number" still returning a string when accessed from javascript

Viewed 72859

I'm new to javascript , I'm trying learning how functions etc in JS and trying to add 2 numbers

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>JS ADD</title>
</head>

<body>

  <h1>Funcitons is JS</h1>


  <input type="number" id="num1">
  <input type="number" id="num2">

  <button type="button" onclick="addNumAction()">
    Add
  </button>

  <script>
    function addNum(n1, n2) {
      return parseInt(n1) + parseInt(n2);
    }

    function addNumAction() {
      var n1 = document.getElementById("num1").value;
      var n2 = document.getElementById("num2").value;

      var sum = addNum(n1, n2);
      window.alert("" + sum);

    }
  </script>

</body>

</html>

If I remove the parseInt() the value is treated as a string only , then what is the point of using <input type="number"> ?please explain to me. what field to use for getting input as a number?

9 Answers

You can use valueAsNumber (described on that page) to get the actual number value. So your code would then be:

function addNum(n1, n2) {
  return n1 + n2;
}

function addNumAction() {
  var n1 = document.getElementById("num1").valueAsNumber;
  var n2 = document.getElementById("num2").valueAsNumber;

  var sum = addNum(n1, n2);
  window.alert("" + sum);

}

Use valueAsNumber

Non-numbers can still be input. Make sure to check for validity, and handle mistakes.

const value = myInput.valueAsNumber
if (isNaN(value)) return // or other handling

If you require updates on every change:

myInput.addEventListener("change", () => {
    const newValue = myInput.valueAsNumber
    if (isNan(newValue)) return

    // Handle change
})

You can also try to convert a number string into a number by using the + operator:

const ns = '3'
console.log(typeof ns)
console.log(typeof +ns)

Or you can safely convert only if it is able to do so:

const ns = '3'
const s = 'hello'

const toNum = v => !!+v ? +v : v

console.log(typeof toNum(ns))
console.log(typeof toNum(s))

The above snippet uses + to convert a value to a number. If it is unable to do so, +v returns NaN. It then use ! to convert NaN into a boolean and then use another ! to negate the boolean.

If you are using variables in your html, try the following:

    <input type="number" (focusout)="(modifiedVal = +modifiedVal)" value="modifiedVal">

Here, modifiedVal is the variable and '+' before variable converts the variable into number.

Related