Organizational Research By

Surprising Reserch Topic

Javascript adding integers


How do I add a simple integer to another integer in Javascript?

I'm getting NaN as the value for total.

 type="text/javascript">
var total = 0;
document.getElementById("dds1").onkeyup = function() {
    total = total + parseInt(this.value,10);
    updateIt();

};

function updateIt() {
//tofixed(2)
    document.getElementById("mySpan").innerHTML = total;
}

But if I do the following:

total = parseInt(this.value,10);

asked May 19, 2015 in JAVASCRIPT by rajesh
0 votes
9 views



Related Hot Questions

1 Answer

0 votes

The problem is that you execute the addition read the input value on every keyup. If the user, for instance, presses BACKSPACE to clear the input, the value will be an empty string, which will result in NaN after parseInt. And once you have NaN (in your total variable), you cannot get rid of it anymore.

Try this:

document.getElementById('dds1').onkeyup = function() {

    var value = parseInt(this.value, 10);

    if ( !isNaN(value) ) {
        total += value;
        updateIt();    
    }

};

Here, you first check if the input value can be parsed as a number. If not, you just disregard it.


Another way of doing it would be this:

document.getElementById('dds1').onkeyup = function() {
    var value = parseInt(this.value, 10);

    isNaN(value) && return;

    total += value;
    updateIt();
};

Here, if you read an input value that cannot be converted into an number, you just return the function altogether.

answered May 19, 2015 by rajesh

...