10

I am new to javaScript. I am building a calculator here

I have stored the input values in variables so that I can eventually manipulate the results to perform calculations based on input. For now I just want all of the values to add together.

However, rather than adding, they are concatenating. I used parseInt to prevent javascript from viewing the numbers as strings, and typeOf reveals that they are numbers.

Here is my javascript:

$(document).ready(function() {

var theTerm = $("#theTerm").val();
var theRate = $("#theRate").val();
var thePrice = $("#thePrice").val();
var theTax = $("#theTax").val();
var theDown = $("#theDown").val();
var theTrade = $("#theTrade").val();
var theResult = parseInt(theTerm + theRate + thePrice + theTax + theDown + theTrade, 10);

$("#calculate").click(function(){
    alert(theResult);
    alert(typeof(theResult));
});

}); 

and the HTML:

<div id="calculator">
<span id="calculatorHeader">Monthly Payment Calculator</span>
<table style="margin:0 auto;">
    <tr>
    <td style="width:40px;">Term
        <input id="theTerm" size="5" value="7" name="term" style="width:35px" />
    </td>
    <td style="width:40px;">Rate(%)
        <input id="theRate" size="5" value="7" name="apr" style="width:35px" />
    </td>
    <td style="width:55px;">Price($)
        <input id="thePrice" size="6" maxlength="7" name="price" style="width:50px" value="7" />
    </td>
    <td style="width:40px;">Tax(%)
        <input id="theTax" size="4" maxlength="7" name="tax" style="width:35px" value="7" />
    </td>
    <td style="width:40px;">Down($)
        <input id="theDown" size="5" maxlength="7" name="downPmt" style="width:35px" value="7" />
    </td>
    <td style="width:40px;">Trade($)
        <input id="theTrade" size="5" maxlength="7" name="trade" style="width:35px" value="7" />
    </td>
    <td style="width:78px;">Est.Monthly Pmt
        <input id="theResult" size="7" maxlength="7" name="result" style="width:75px" value="0" />
    </td>
    </tr>
</table>
<button type="button" id="calculate">Add Boxes!</button>
</div>
6
  • 3
    Use parseInt on each number, then sum them up. Commented Mar 15, 2014 at 3:41
  • 2
    parseInt is not an environment that causes everything to be treated as numbers inside it. It is a function that takes a string and returns an integer. You have several strings; go get several integers. Commented Mar 15, 2014 at 3:41
  • What you're missing is that .val() returns what the user typed which is a string. When you add strings, you get another string. And if you add "13" + "26", you get "1326", not 39. Commented Mar 15, 2014 at 3:54
  • @jfriend00 I figured that out by using typeOf, googled what to do and then used code in my original post (with parseInt). What was strange is that typeOf then returned "number" yet still concatenated result as if it were a string! Commented Mar 15, 2014 at 4:24
  • You added strings and THEN converted to a number. You have to convert to a number BEFORE you add. Commented Mar 15, 2014 at 4:30

5 Answers 5

21

Change line and apply parseInt to each obj as follow

var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);
Sign up to request clarification or add additional context in comments.

5 Comments

This does work, but I don't want to use parseInt every time I need the variable. Is this the only way to do?
yupp it necessary to convert string in to integer value and you may also try the @mohit pandey's answer to convert string into int.
@HelloWorld You don't need to use it each time and repeat yourself, see my answer.
You really should use 10 as the second parameter of the parseInt function
Nowadays you can just use var theResult = [theTerm, theRate, thePrice, theTax, theDown, theTrade].reduce((a, b) => a + Number(b), 0);.
6

Instead of using parseInt, you can multiply number by 1. Its much faster and easier method to covert datatype.

$(document).ready(function () {
    var theTerm = $("#theTerm").val() * 1;
    var theRate = $("#theRate").val() * 1;
    var thePrice = $("#thePrice").val() * 1;
    var theTax = $("#theTax").val() * 1;
    var theDown = $("#theDown").val() * 1;
    var theTrade = $("#theTrade").val() * 1;
    var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;

    $("#calculate").click(function () {
        alert(theResult);
        alert(typeof (theResult));
    });
});

JSFiddle: http://jsfiddle.net/RqzPk/14/

2 Comments

If you're going for fast and compact, then just put a + in from of them: var theTerm = +$("#theTerm").val(). Personally, I don't think these "trick" conversions are as readable as an explicit numeric conversion (easy to miss the developer's intent).
@jfriend00 these both work too. I can see where each of these methods would be useful depending on the situation.
3

Tidy up your code a bit and avoid repetition:

DEMO

$(document).ready(function() {
    $("#calculate").click(function(){   
        var inputs = $("input"), theResult = 0;  // `inputs` is the list of all input elements

        for(var i = 0;i < inputs.length; i++)  // iterate over all inputs
            // parse their value, in base 10, and add to the theResult
            theResult += parseInt(inputs[i].value, 10); 

        alert(theResult); // 42
    });
});

4 Comments

In order to do simple addition, this is optimal. However, as I stated in the question, this will be a calculator that will perform functions other than simply adding the numbers in the fields. I am not sure your solution would work when I want to multiply or add a percentage to the total.
@HelloWorld Ok, I see that you won't perform just addition. Apologies then.
@HelloWorld P.S. you might be interested in parseFloat, because if the user will enter decimal value, like 2.2, then it will become 2 if you use parseInt
OK got it! parseInt converts datatypes to whole numbers. parseFloat converts datatypes to floating point numbers.
1

you have to use parseInt function of java script.

for ex: var theTerm = parseInt($("#theTerm").val());

demo

1 Comment

I did use parseInt. You do need to add the base # parameter don't you?
1

You're concatenating the strings with + and then you're converting that concatenated result to an int.

You want to convert to an integer before you add. Something like:

var theTerm = parseInt($("#theTerm").val(), 10);
...
var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;

2 Comments

Just to expound upon your answer... The second parameter in ParseInt is asking for a base of the number. So base 10 would be a number that is made up of 0-9. Base 16 would be hexidecimal where the number would be represented by 0-F.
OK! now I wont have to use parseInt every time I need the variable as I build.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.