Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - parseInt always returns NaN?

long story short, i was trying to validate a phone field. ive added the isNaN and parseInt for checking the " " in the field but that said

This below never validates to true..what am i missing?

if(isNaN(parseInt(phone))){
        error.text("Sorry but this phone field requires numbers only");
        return false;
    } else {
    return true;

    }

it always fails...it never reads true even when i enter a number in the field and submit. i always get the error mssg.

EDIT: I am testing input values from a form, phone is the name of the field.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Various ways to coerse JS strings to numbers, and their consequences:

Results of converting various strings using the above techniques
(source: phrogz.net)

I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

Edit: Based on your comment, if using phone.val() fixed it then

  1. You were using jQuery (which you never mentioned, and should have), and
  2. You actually had/have a jQuery object, wrapping one or more DOM elements (probably just one).

Whenever you do var foo = $('…'); then the foo variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0]; or var fooEl = foo.get(0);…but even then you still have a DOM element and not a particular property of that.

For form inputs, you need to get the .value from the DOM element, which is what the jQuery .val() method does.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...