Skip to content
Advertisement

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

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?

Advertisement

Answer

It’s normal you get a string.

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email type will show a keyboard with the @ and ‘.’ on the keyboard and number will show a numeric keyboard.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement