Alex
Alex

Reputation: 3958

JavaScript var not being recognized as a number

I have an HTML div, which I use JavaScript to retrieve the value from, as below:

    var oCreditStatus = document.getElementById('creditStatusField');

    var oOrigValue = oCreditStatus.value;

var oOrigValue will always be a number, and sometimes 0 (Zero).

I now want to increment or decrement the number by 1. However, when I do the following:

var oNewValue = oCreditStatus.value + 1;

I get the value 01, then 011, which is wrong as I want 1,2.

I know it is not recognizing it as a number, but how do I get it to do so.

Upvotes: 0

Views: 1948

Answers (5)

Amit Joki
Amit Joki

Reputation: 59232

var oOrigValue will always be a number, and sometimes 0 (Zero).

Just pass it to Number function since oOrigValue is always a number. (Note: 0 is also a number)

var oOrigValue = Number(oCreditStatus.value);

There are several other ways of doing the same by prefixing it with + and ~~

Upvotes: 3

Michał Dudak
Michał Dudak

Reputation: 5048

In fact oOrigValue is not a number, it's a string. To be able to add another number to it, you'll have to parse it first. There is several methods to do it:

var parsedValue = parseInt(oOrigValue, 10); // remember about the second parameter - the radix

or simpler, but less readable

var parsedValue = +oOrigValue;

Upvotes: 2

Phil Gabardo
Phil Gabardo

Reputation: 142

You need to parse oCreditStatus.value as an int

var oNewValue = parseInt(oCreditStatus.value) + 1;

Upvotes: 0

indrarajw
indrarajw

Reputation: 198

try to this

var oCreditStatus = document.getElementById('creditStatusField').value*1;

Upvotes: 0

mehulmpt
mehulmpt

Reputation: 16547

You can't. Javascript engine will read it as a text/string. You've to use following code:

Edit. Use a radix (base 10) Thanks to @James for revision.

var oCreditStatus = document.getElementById('creditStatusField');

var oOrigValue = parseInt(oCreditStatus.value, 10); // use parseFloat for decimal.

Upvotes: 5

Related Questions