I want to add comma to numbers every three digits on Textboxes.
I'm using this code but it not works.
Where am I wrong?
$(function () {
$.fn.digits = function () {
return this.each(function () {
$(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
$("#Test").bind("change keyup keydown paste blur", function (e) {
$("#Test").digits();
});
});
You can use type="text" and then add commas to the number in the onchange event.
Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc.
Try the following:
// "1234567".commafy() returns "1,234,567"
String.prototype.commafy = function() {
return this.replace(/(.)(?=(.{3})+$)/g,"$1,")
}
$.fn.digits = function () {
return this.each(function () {
$(this).val($(this).val().commafy());
})
}
JSFiddle http://jsfiddle.net/BrUVq/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With