I have a quick form field where you can enter your age. When the user enters his/her age in words (like: twenty), it should give a quick alert telling that the age should be in numbers.
This is my code and it doesn't work
var formAge = $("<input class='inputClass' type='text' placeholder='bv.: 21'/>").appendTo(formDiv);
$(formAge).blur(function(){
if($(this).val() == isNaN){
alert("insert a number");
}
})
I have a quick form field where you can enter your age. When the user enters his/her age in words (like: twenty), it should give a quick alert telling that the age should be in numbers.
This is my code and it doesn't work
var formAge = $("<input class='inputClass' type='text' placeholder='bv.: 21'/>").appendTo(formDiv);
$(formAge).blur(function(){
if($(this).val() == isNaN){
alert("insert a number");
}
})
Share
Improve this question
edited Oct 5, 2015 at 10:48
Anders
8,65310 gold badges60 silver badges99 bronze badges
asked Apr 3, 2015 at 10:31
pu4cupu4cu
1655 silver badges21 bronze badges
2
- 1 Replace your if condition with this condition if(isNaN($(this).value)){ – stanze Commented Apr 3, 2015 at 10:38
- You'd be better of with a simple regex. – lshettyl Commented Apr 3, 2015 at 11:21
2 Answers
Reset to default 3if(isNaN($(this).val())){
alert("insert a number");
}
You need to use javaScript isNaN() function.
Change your code like
if(isNaN($(this).val()))
{
alert("insert a number");
}
var a = isNaN(123) + "<br>";
var b = isNaN(-1.23) + "<br>";
var c = isNaN(5-2) + "<br>";
var d = isNaN(0) + "<br>";
var e = isNaN("Hello") + "<br>";
var f = isNaN("2005/12/12") + "<br>";
var res = a + b + c + d + e + f;
Output
false
false
false
false
true
true