jQuery: How to add thousands separator in multiple div? [duplicate]
I improvised the answer in the comment. What you would need is the below code only. Check this out and also the fiddle:
$(document).on('keyup', '.test', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
Fiddle: http://jsfiddle.net/praveenscience/R8JrF/1/
The reason why it didn't work was, once you make changes, you need to remove all the commas, and do the formatting again, which was not done in the OP's code as well as the other answer code.
Use Number.prototype.toLocaleString();
check here
var no = 3456;
no.toLocaleString();
Gives 3,456
Your problem is that when you get to the 8th digit, the intermediate result has already two commas in it. Yet,
val = val.replace(',', '');
does only replace the first one. You would need to provide a regular expression with the global flag set:
val = val.replace(/,/g, '');
Updated, working fiddle
Try Intl.NumberFormat instead
var number = 1000000;
console.log(new Intl.NumberFormat().format(number));
// 1,000,000
Solution of your issue: https://jsfiddle.net/mf2s48jo/