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
The value of a
<input type="text">is always a string. You can, however, parse it as an number by usingparseInt. It will result inNaNif not number could be parsed from the string. Don’t forget you’ll have to useisNaNfor this, asmyNumber === NaNisn’t a valid operation.Even better, use
isNaN(+searchKey), as the unary operand will callToNumber. However, this will ignore whitespace.