0

Possible Duplicate:
Is there a (built-in) way in JavaScript to check if a string is a valid number?

I have an input search bar in HTML

<form class="form-inline" action="javascript:displayResult()">          
    <input id="searchKey" >
    <button onclick="result()" type="button" class="btn btn-warning btn ">
          Go
    </button>                   
</form>

This is the Javascript function

function result() {     
    search($('#searchKey').val());    

    if(typeof(searchKey)=="number") { // checking if this is a number
       someFunction();
    }
};

The problem is , for each entry to the search bar I get the value as a string , even if it is "hello" or 9789 in the search bar . I used alert(typeof(searchKey)); to verify and it always return the type as string

I am trying to differentiate between a number and a string at the search bar , I am sure there is a better way to do this , but I am unsure about why this is not working

I cannot use parseInt() as I need to differentiate between text and number dynamically

Community
  • 1
  • 1
alex
  • 235
  • 3
  • 11

3 Answers3

5

The value of a <input type="text"> is always a string. You can, however, parse it as an number by using parseInt. It will result in NaN if not number could be parsed from the string. Don't forget you'll have to use isNaN for this, as myNumber === NaN isn't a valid operation.

Even better, use isNaN(+searchKey), as the unary operand will call ToNumber. However, this will ignore whitespace.

9.3.1 ToNumber Applied to the String Type

ToNumber applied to Strings applies the following grammar to the input String. If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.

[see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf for the actual rules]


11.4.6 Unary + Operator

The unary + operator converts its operand to Number type. The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).
Zeta
  • 103,620
  • 13
  • 194
  • 236
3

A text input field always contains a string value. Try if (!isNaN(searchKey)) to test for numeric value. Alternatively you could use a Regular Expression: /^\d+$/.test(searchKey)

KooiInc
  • 119,216
  • 31
  • 141
  • 177
3

use

if(!isNaN(searchKey))

instead of

if(typeof(searchKey)=="number")
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101