Reputation: 131
I have two buttons and there is a form in between. One button says "+" and the other "-". I am trying to make increment/decrement buttons, but it is not properly working. It seems like addition is causing a problem where increment is not happening, and instead, concatenation is happening. For example, when the form value is 0, and "+" button is pressed, it changes the 0 to 01. My JavaScript code has
//assume the oldValue read 0 from the form
newValue = oldValue + 1
alert(newValue); //this returns 01 instead of 1
When the oldValue is 01 and increment again, it returns 011. Why is this not incrementing, but concatenating the 1 at the end? Surprisingly, decrement is working perfectly with the same code except that I have a minus where there is a plus.
How can you increment a form value in peace? and can anyone explain why "+ 1" does not work?
Upvotes: 0
Views: 1062
Reputation: 91
CASE 1:
var a=1;
var b=2;
alert(a+b);// RESULT WILL BE 3
CASE 2:
var a='1';
var b=2;
alert(a+b);// RESULT WILL BE 12
If you are getting values from a Form or something , your value will be treated as a string (like '1') . You can convert if to number/int by Using the Keyword
Number
, Like below
alert(Number(a)+b);
Upvotes: 1
Reputation: 26258
Try this:
newValue = parseInt(oldValue) + 1;
This is happening because oldValue datatype is string and when you add a Int to a String then the output is also a string. So you have to convert it into a number before adding some int value into it.
Upvotes: 1
Reputation: 1632
newValue = Number(oldValue) + 1
I think you forgot to convert string to int.
Upvotes: 1