68

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?

2

9 Answers 9

69

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.

5
  • Is there any way to get the input as a number that can be used like a javascript number data type , or is receiving as string and converting the standard way to do this? Mar 4, 2016 at 9:05
  • 8
    You will have to use parseInt in this case. Mar 4, 2016 at 9:07
  • If that answered your question, would you mind accepting the answer? Mar 4, 2016 at 9:08
  • @SainathS.R Please check the link in secretgenes's answer. A number can have many different formats and still be a number. It's good news that JavaScript doesn't hide the actual value. Mar 4, 2016 at 16:29
  • 3
    The purpose of <input type="number"> and a few other types is also to provide a useful value in the valueAsNumber property. Nov 22, 2020 at 2:32
31

Neither HTML nor HTTP really have the concept of data types (possibly because they aren't programming languages to begin with) and everything is a string. When you use another language to reach that information you may sometimes get some amount of magic as a feature (for instance, PHP will generate arrays from GET/POST fields that have paired square brackets on their names) but that's a feature of such other language.

In this case, .value belongs to the DOM API and such API does have types. But let's see how it's defined. The <input> tag is represented by the HTMLInputElement interface and the value property is of type DOMString:

DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.

In other words, type="number" is a hint to implement client-side validation and appropriate GUI controls but the underlying element will still store strings.

Numeric keyboard screen-shot
19

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);

}
17

tl;dr you're doing everything correctly already, just keep using parseInt.

type="number" tells the browser that the user should only be allowed to enter number characters, but deep down, it's still a text field.

1
  • 1
    This should have been the accepted answer because it is exactly what it is.
    – Chris22
    Feb 21, 2020 at 22:50
9
  1. HTML Input elements are documented to return string representing a number. See the documentation here : Documentation of HTML Input

  2. When you set input type="number" then these input field don't accept non numeric input but at the same time it doesn't make the input value type "number". The reason is inputted number contain digits as a subset of the valid characters, but they also contain completely non-numeric characters like spaces, hyphens and parenthesis.

1
  • 1
    Link is broken.
    – User
    May 20, 2021 at 10:30
7

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
})
3

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.

2

type="number" only for browser validation. But you get a string. And you may use parseInt(num1) or + before string.

function addNum(n1, n2) {
  return +(n1) + +(n2);
}
4
  • 4
    parseInt(num1) without specifying a radix is the definition of asking for trouble. For decimal numbers, use parseInt(num1, 10) – or just cast the string to a number with the plus sign trick. Dec 6, 2017 at 14:28
  • What is a "radix" and why is it asking for trouble?
    – JCLaHoot
    Feb 11, 2018 at 22:07
  • 2
    Radix is the numeral system's base (en.wikipedia.org/wiki/Radix) so radix=16 will parse hexadecimal numbers, radix=2 binary and radix=10 decimal. Usually you'd use radix=10. Sep 24, 2018 at 8:02
  • type="number" is not only for browser validation but for valueAsNumber too. Also you can write your own inputCheck function based on type attribute which'll check type and make conversion string to number and pattern checking Jun 15, 2020 at 9:48
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.