JavaScript .value question

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

JavaScript .value question

Post by icesolid »

I have a simple if statement that determines if the number entered in a text input is greater than 150. It works as long as the number entered is 3 digits. However if someone enters 60 in the input box, which is less than 150, the if statement is true because it puts a 0 at the end and makes the 60 a 600. My code for my if statement is below:

Code: Select all

if(document.getElementById('process_form').charge.value > "150")
How can I fix this?
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: JavaScript .value question

Post by mintedjo »

I dont think you should be using "150"
putting quotes around the number makes it a string object and comparing strings with numbers is generally not a good idea.

Also, how do you know that its adding a "0" to the end and making it 600?
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: JavaScript .value question

Post by kaszu »

Code: Select all

if(parseFloat(document.getElementById('process_form').charge.value) > 150)
It works with 60 because character "6" value is greater than "1" (like "b" > "a"), that's why "60" becomes the winner :)
Last edited by kaszu on Wed Dec 10, 2008 3:55 pm, edited 1 time in total.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: JavaScript .value question

Post by pickle »

Change "150" to 150, then run the value of the field through parseInt().

Something's acting funky if it appends 0 to the value - that's not supposed to happen.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply