Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input value is a string instead of a number

When i add a number to the input it doesn't change the value that stays at 5 and when i go in the console and type uw.value i get "6" back instead of 6 which i typed in the input on the web how do i get a number back instead of a string?

<form>
    <input type="number" id="wakken" type="number" value=5><br>
    <input max="30" min="0" name="ijsberen" placeholder="Ijsberen" id="ijsberen" type="number" value= "5"><br>
    <input max="30" min="0" name="wakken" placeholder="Penguins" id="penguins" type="number" value= 0><br>
    <input type="button" value="submit" onclick="check()">
</form>      
 var uw = document.getElementById("wakken")
 var ui = document.getElementById("ijsberen")
 var up = document.getElementById("penguins")
like image 955
Knack Kwenie Avatar asked Jan 08 '15 21:01

Knack Kwenie


People also ask

Is input value a string?

Input value is a string instead of a number.

Why is input type number a string?

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.

How do you check if input value is string or number?

To check if an input's value is a valid number in React: Check if the input's value is not an empty string or contains only spaces. Pass the value to the isNaN() function. If isNaN returns false , the value is a valid number.

What is an input value?

< input type = "button" value = "Submit" >


1 Answers

Check out HTMLInputElement.valueAsNumber:

The value of the element, interpreted as one of the following in order:

  1. a time value
  2. a number
  3. null if conversion is not possible

var testInput = document.getElementById("test-input");

function handleInput(e){
  var value = this.valueAsNumber;
  console.log("type: %s, value: %o", typeof value, value);  
}

testInput.addEventListener("input", handleInput);
  
handleInput.call(testInput);
<input type="number" id="test-input" type="number" value=5>

This will return NaN for non-numerics or non-finite numbers.

like image 122
canon Avatar answered Oct 24 '22 10:10

canon