Thursday, 12 September 2013

How can I add commas in jQuery to all elements with same class?

How can I add commas in jQuery to all elements with same class?

This is what I'm trying:
I give all elements that I'd like to format with a comma the class addcomma.
So my HTML looks like this:
<div class="addcomma">1234567</div>
<div class="addcomma">1234567</div>
<div class="addcomma">1234567</div>
And I attempt to add commas in jQuery with the following:
function addCommas(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
$('.addcomma').each(function() {
var curInt = $(this).text();
newInt = addCommas(curInt);
$(this).text(newInt);
});
Why doesn't this work, and what would you suggest as an alternative?

No comments:

Post a Comment