Search code examples
jquerycalculatorjquery-calculation

Calculator: Get total sum from single input


I'm currently building my first calculator in jQuery and I have some problems with the total sum of the value in the input. I'm not using more than one input because I want to keep it simple and easy to use. The code below prints NaN and I don't understand why.

$('body').on('click', '#method-getsum', function() {
    var sum = 0;
    var string = $('input[name="fieldtext-calculate"]').val();

    if(string.length != 0) {
        sum += Number(string);
    }

    alert(sum);
});

Have I missed something? You can see it all in action here: http://jsfiddle.net/edgren/QTjWR/ (this demo contains the correct solution with the eval function (my calculator is not for real project. Just with "play around" project))

Thanks in advance.


Solution

  • When you input something like 1+2, your code will then call Number("1+2"). That's incorrect, since Number() expects single number (not the addition) as its argument. It will not perform operation parsing and interpretation for you, you must write the code yourself.

    If it's just a toy project, use eval instead of Number (avoid eval in real projects, it creates security issues).