0

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.

Airikr
  • 6,258
  • 15
  • 59
  • 110

2 Answers2

1

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).

rburny
  • 1,559
  • 1
  • 9
  • 28
  • Ah! So that's why I'm getting `NaN` :) But when I am testing `parseInt` it only shows the first number (for example the input have 50+3 and it will then only show 50). – Airikr Jan 23 '13 at 19:08
  • You want to use `split` or something similar to get it into an array. – akousmata Jan 23 '13 at 19:10
  • Many thanks :) I know now how I will fix my problem. Thanks once again! – Airikr Jan 23 '13 at 19:11
0

Might be you're using a keyword for a variable name. Try changing your code to:

var fieldText = $('input[name="fieldtext-calculate"]').val();

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

EDIT Nevermind, the value that is returned from $('input[name="fieldtext-calculate"]').val(); is the string '7 + 8 + 9'. Try getting a distinct value by splitting on the + sign to get the numbers into and array then loop through the array.

akousmata
  • 1,005
  • 14
  • 34