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

JavascriptHtmlWebInputNumbers

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

https://i.stack.imgur.com/9599A.png" width="220" alt="Numeric keyboard screen-shot">

Solution 3 - Javascript

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.

Solution 4 - Javascript

  1. HTML Input elements are documented to return string representing a number. See the documentation here : Documentation of HTML Input
  1. 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.

Solution 5 - Javascript

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

}

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSainath S.RView Question on Stackoverflow
Solution 1 - JavascriptArno ChauveauView Answer on Stackoverflow
Solution 2 - JavascriptÁlvaro GonzálezView Answer on Stackoverflow
Solution 3 - JavascriptwebbView Answer on Stackoverflow
Solution 4 - JavascriptsecretgenesView Answer on Stackoverflow
Solution 5 - JavascriptChris ShepherdView Answer on Stackoverflow
Solution 6 - JavascriptGiboltView Answer on Stackoverflow
Solution 7 - JavascriptJulia ShirokovaView Answer on Stackoverflow
Solution 8 - JavascriptNathanView Answer on Stackoverflow
Solution 9 - JavascriptSakshi KaushikView Answer on Stackoverflow