views:

151

answers:

4

Hello all,

I am using JQuery to get the contents of a div, which only contains a price in dollars and I would like to add $99 to it, but its text, so when I do the below it won't work.

$('#price_' + part[0]).text($('#price_' + part[0]).text() + 99);
//Changes the div contents to $10099 - if it the contents was $100 to start with

So the question is how can I add the numeric values?

Thanks all

Edit

Please note some numbers can contain a comma i.e. $1,200

+2  A: 

Get numerical substring and cast it to a number:

$('#price_' + part[0]).text("$" + (+($('#price_' + part[0]).text()).substring(1) + 99)); 

Note the use of the unary + operator to cast the string into a number, and the use of substring to get everything after the 1st ($) character in the string.


UPDATE

Since you mentioned the value can contain a comma, you'll be better off breaking this down a bit and performing a string replace:

var div    = $('#price_' + part[0]);  // get a ref to the div

// replace occurrences of `$` or `,`, cast to a number and add 99
var amount = +div.text().replace(/[$,]/g, '') + 99;

// set the new text to the div
div.text("$" + amount);
Andy E
I get $NaN? I think its because the price I tried on it contains a comma (,)!
Abs
@Abs: Yes, if you have thousand separators in the string, casting will produce `NaN` and `parseInt` would result in a very innacurate number (1,256 would become 1 for instance). You're best off performing a `replace()` on the string before casting - see my update.
Andy E
Thank you Andy, that worked perfectly. I just put together a quick function to put the comma back in and everything is working great. Thank you! :)
Abs
A: 

Use parseInt:

var price = $('#price_' + part[0]);
price.text(parseInt(price.text()) + 99);
PetersenDidIt
`parseInt` will not work on a string that doesn't start with a number
Andy E
A: 

You'll have to convert the text to int/float before doing the arithmatic

$('#price_' + part[0]).text( parseInt( $('#price_' + part[0]).text() ) + 99);

parseFloat in place of parseInt if you need/want.

Jamiec
`parseInt` will not work on a string that doesn't start with a number
Andy E
+1  A: 

Something like this should work

 var str = $(...).text();
 var sum = parseInt(str.replace(/\D/g, ""));
 $(...).text("$" + (sum + 99))
stereofrog
you'll probably need to add in fullstops to the reg ex and use parseFloat rather than ParseInt
Matt Smith