View Full Version : Help with javaScript

07-03-2011, 11:16 PM
I am learning javaScript to put into my arsenal of coding tools for employment or to further my abilities in my business. I am reading Head First and in there I came across some code that seems redundant to me. Her is what they have:

if (document.getElementById("pickupminutes").value == "" || isNaN(document.getElementById("pickupminutes").value)
alert ...

Now, I don't know the purpose for the second line except to check if it is a number. However, I think I could solve this with:

if (isNaN(document.getElementById("pickupminutes").value == "")

I think it would save coding if I could check both if it is a number and if it is and empty string all in one line. Could anyone tell me if this line would not work and why?

Thanks all.

07-03-2011, 11:59 PM
It will not work

1. Mismatch in number of opening and closing parentheses
2. isNaN is a function that expects one argument parameter. It will return true or false depending on whether or not the argument is a number. Then you have the == compare operator which will also return true or false. So you would have either true or false as parameter for isNaN. So isNaN would always return true.

07-04-2011, 06:52 PM
Your code:

if (isNaN(document.getElementById("pickupminutes").value == ""))
It doesn't work because of:
1-Missing ).
2-isNaN() return true when its argument is not a number, and in your case the argument is a boolean so isNaN() evaluates always to true.
The right code is:


You can change parseFloat() by parseInt() if the number shouldn't have a floating decimal point.

07-04-2011, 08:37 PM
I thank you both for your input. As for devnull69's reply, the purpose of what I was trying to accomplish was to check, one to see if they entered a number, and second to check to see if the field was left blank. I always attempt to accomplish as much as I can with as little code as possible because, at least for the most part, it makes the maintenance of my code easier. If I cannot check both in the one line, as Hamza7 has explained, their will be no point not to add the second line.

If anyone has a solution that would eliminate the second line, I would be all ears. The suggested code from the book was:

if (document.getElementById("pickupminutes").value == "" || isNaN(document.getElementById("pickupminutes").value)
alert ...

I am trying to get the solution to work without having to do two checks, eliminating the OR statement. Is there any way to do this? BTY the alert is to tell the customer that they need to put in the amount of minutes for pick up, or if the value is not in numeric form that they need to enter it in numeric form, eliminating the possibility of an entry that would not make sense in the number of minutes for pick up.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum