skos
skos

Reputation: 4212

JQuery Simple Addition Issue

I am using Jquery.Ajax and want to do some addition with the ajax response and predefined variable. My code is as follows -

success: function(response)
{
    $('#net_amount').html("$"+(credit+response));
}

Assuming 'response' as 10 and 'credit' as 20, it prints 2010. I want it to be 30 (20+30).

What shall I do ?

Upvotes: 1

Views: 414

Answers (5)

A.Wack
A.Wack

Reputation: 478

Another solution is to multiply the values of credit and response by 1 at the same time you're adding them. This will force JS to treat them as numeric values rather than strings.

success: function(response)
{
    $('#net_amount').html("$"+((credit*1.00)+(response*1.00)));
}

Upvotes: 0

K6t
K6t

Reputation: 1845

use parseInt() or parseFloat() its convert into Integer format

E;g:

     var     credit =   '30';
            response=   '20';

     alert(typeof(response)); // string
     alert("++++++++++++"+"$"+(parseInt(credit)+parseInt(response))+"++++++++++++");

if your value as in Integer, then u no need to go for parseInt(),parseFloat()

     var   credit = 30;
          response= 20;

     alert(typeof(response)); // // Integer 
     alert("++++++++++++"+"$"+((credit)+(response))+"++++++++++++");

Upvotes: 0

Abe Petrillo
Abe Petrillo

Reputation: 2447

The response or credit is being treated as a string. (probably the response).

success: function(response)
{
    $('#net_amount').html("$"+(parseInt(credit)+parseInt(response)));
}

The above will give you the expected result

Upvotes: 0

cillierscharl
cillierscharl

Reputation: 7117

All you would need to do is parse the value to an Integer first as follows:

$('#net_amount').html("$" + ( parseInt(credit) + parseInt(response) ));

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Because + is used for concatenation in javascript as well as the addition, you need to ensure the type of your variables is numerical, not a string.

Your options are to use parseInt() and parseFloat(). I would suggest the latter as you are dealing with monetary values in your example.

success: function(response) {
    $('#net_amount').html("$" + (parseFloat(credit) + parseFloat(response)));
}

Upvotes: 3

Related Questions