json2021
json2021

Reputation: 2317

Why is javascript showing typeof as "string" when its a number?

I am trying to preform some form validation, and for some reason when I enter a number on the input field it shows the typeof as a string.

I really can't wrap my head around this. I have tried researching online but couldn't find an answer.

Any help would be really appreciated. Below is my code a link to jsfiddle example.

Thank you in advance

https://jsfiddle.net/eldan88/2xb47g78/

<button>Check if number</button>
<input id="number" type="number">

<script>

$("button").click(function () {

    var number = $("#number").val();

    alert(typeof (number));

    if(typeof number !== "number"){
        alert("not a number");
    }




});


</script>

Upvotes: 2

Views: 5316

Answers (6)

Francis Meng
Francis Meng

Reputation: 86

This is because the value of an input is always a string. For example, when I'm entering 3, the actual value is not the number 3, it is the string "3". To check if it is not a number, use isNaN(), a Javascript native function to check if something is not a number. For example, when you run isNaN("3") it will return false, since 3 is a number.

Upvotes: 5

Moe
Moe

Reputation: 1599

var myVar=5
alert(typeof myVar) //Number

var myVar = "5"
alert(typeof myVar) //String

var myVar = "5"
var vResult = parseInt(myVar);
alert(typeof vResult) //Number

In your case what's returned from the text box is .val() which is always a string.

Upvotes: 0

TAGraves
TAGraves

Reputation: 1409

As others have stated, HTML input elements always store their values as strings, even if those values are "numeric strings." Here's one way of making your validation work:

$("button").click(function () {

    var number = $("#number").val();

    alert(Number(number));

    if(isNaN(Number(number))){
        alert("not a number");
    }

});

Upvotes: 0

crc442
crc442

Reputation: 627

The value property of an input element is always stored as a string, so typeof is always going to return "string".

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

You need to write your own custom functions to determine the type of the input.

Upvotes: 3

BenG
BenG

Reputation: 15154

Here on w3.org. it adivses:-

value = floating-point number #

A string representing a number.

Upvotes: 0

TankorSmash
TankorSmash

Reputation: 12747

The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.

http://www.w3.org/TR/html-markup/input.number.html

So no matter what, an input contains a string.

Upvotes: 1

Related Questions