最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery check if number is typed isNaN - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3
if(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
发布评论

评论列表(0)

  1. 暂无评论