1

I have a span element which holds a number such as 1,568.

When a button is clicked, I need that number to increment by 1. So 1,568 becomes 1,569.

If I just get the value and add + 1 to it, the value becomes 2:

("#artist-fan-count").text(parseInt($("#artist-fan-count").text()) + 1);

Should I try to remove the comma and then run the code above? If I do the line below, nothing happens -- which leads me to believe I'm doing it wrong. Shrug.

$("#artist-fan-count").text().replace(',', '');

Any tips?

Wouter J
  • 41,455
  • 15
  • 107
  • 112
Mike
  • 980
  • 3
  • 15
  • 29

5 Answers5

3

Try the following to remove the comma and increment by 1:

var fanCountEl = document.getElementById('artist-fan-count');
fanCountEl.innerHTML = parseInt(fanCountEl.innerHTML.replace(',', '')) + 1;
Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73
3

You can remove all the commas, parseInt, increment, and then reconstruct your number with the commas, like so:

var $e = $("#artist-fan-count");
var num = parseInt($e.text().replace(',','')) + 1;
$e.text($.fn.digits(num));

using digits from: Add comma to numbers every three digits

Community
  • 1
  • 1
Mohamed Nuur
  • 5,536
  • 6
  • 39
  • 55
2

Well, you have to write your replaced text back:

$("#artist-fan-count").text($("#artist-fan-count").text().replace(',', ''));

after that, you can parse your text as an integer, add your number and (if you want to) put that comma back in place.

If you want to reassemble your Text:

var number = $("#artist-fan-count").text();
$("#artist-fan-count").text(parseInt(number/1000)+","+(number%1000));
Tobi
  • 1,175
  • 1
  • 19
  • 44
1

You could do that :

var $e = $("#artist-fan-count");
var str = ''+(parseInt($e.text().replace(/,/g,''), 10)+1);
var r = /(\d+)(\d{3})/;
while (r.test(str))  str = str.replace(r, '$1' + ',' + '$2');
$e.text(str);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

You're close, but replace doesn't do it in-place:

$("#artist-fan-count").text($("#artist-fan-count").text().replace(',', ''));
tckmn
  • 57,719
  • 27
  • 114
  • 156