Forum Moderators: open

Message Too Old, No Replies

Increasing Variable Value by a Number

         

Jeremy_H

12:27 am on Mar 11, 2006 (gmt 0)

10+ Year Member



Hello,

With the script I'm writing, I'm trying to increase the value of a hidden field by one. The field starts of at zero, and it will increase by one, each time there is a validation error.

So by default, the value is 0. Then I have this line come after the validation error alert:

document.q.e1.value=document.q.e1.value+1;

If there was one error, I would have hoped the new value would be "1", but written as is, it comes out "01".

Any ideas how I can fix this?

Thanks

Bernard Marx

12:38 am on Mar 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



form element values (and lots besides) are always strings.

The easiest conversion to number is to multiply by 1
(or /1, or -0 ).

document.q.e1.value = document.q.e1.value*1 +1;

There are, of course, issues to deal with such as the value being invalid as a number. You could cover yourself by, say, defaulting the value to zero if the value is invalid.

note: "somestring"*1 => NaN
and NaN evaluates false.

document.q.e1.value = ((document.q.e1.value*1)¦¦0) +1;

Jeremy_H

4:47 am on Mar 14, 2006 (gmt 0)

10+ Year Member



Thank you, that fixed my problem!