Matt Elhotiby
Matt Elhotiby

Reputation: 44066

How do i add a string dollar amount in javascript/jquery?

I have fields that have text like this

$4.00
$5.00
$55.90

and I want to add them in javascript to have a total of $64.90

I have this code

 var total= "";
 $("input:checkbox:not(.select_all):checked").closest("tr").each(function() {
    total += $(this).find(".amount").text().trim();
   });

My solution gives me this

 $4.00$5.00$55.90

Any idea what i am doing wrong

Upvotes: 4

Views: 2039

Answers (1)

Paul
Paul

Reputation: 141829

You're concatenating strings, you need to parse them as numbers first. You'll have to strip off the $ to do that. You also want to initialize total to 0, not to an empty string:

var total = 0;
$("input:checkbox:not(.select_all):checked").closest("tr").each(function() {
    total += parseFloat($(this).find(".amount").text().trim().replace(/^$/, ''));
});

// If you want total to be a string containing the `$` just convert it back:
total = '$' + total;

Upvotes: 7

Related Questions