How would I go about dynamically adding commas as a user is entering numbers? Is there a good number formatter that would help? I have to add these numbers later so I eventually have to remove the commas down the line. But the screen needs to show the commas for better readability.
Asked
Active
Viewed 6.3k times
38
-
1So wait you want a comma to be added after every number? So me typing 123456 would turn out to be 1,2,3,4,5,6? Or are you just replacing spaces with commas? – Tim Meers Apr 13 '10 at 19:02
-
2as macek answers, he most likely wants to add thousands separators. – Adriano Varoli Piazza Apr 13 '10 at 19:26
3 Answers
107
Run the code snippet to see it work
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">

maček
- 76,434
- 37
- 167
- 198
-
You could just skip having to call jQuery again in the keyup function by just using this throughout. Then change var num = $this.val().replace() to this.value.replace(), and $this.val(num.replace()) to this.value = num.replace(). – Bob Apr 13 '10 at 20:45
-
1@Bob, I appreciate your input, but using jQuery's methods at the cost of calling `$()` is widely accepted within the jQuery community. That's *why* jQuery has the methods available in the first place. – maček Apr 13 '10 at 20:48
-
3I was just trying this chunk of code, and in Chrome and FF, it misplaces the commas by 1 place. For example, "1234" -> "1234" and "12345" -> "1,2345" – StoicLoofah Feb 25 '13 at 17:43
-
@maček can you solve the problem in this code if i use backspace comma should be on exact position. jsfiddle.net/23Ccf – Naveed Jul 08 '13 at 13:57
-
3@Naveed (and everyone), it's been long overdue, but I've made updates to this code to make it a little more reliable. The regexp has been improved to address some issues too. This also allows a user to press backspace and have commas still be correct. – maček Jul 08 '13 at 19:38
-
-
-
-
-
2
-
5
Here's an implementation of @maček's answer in vanilla JS if you don't want to use jQuery:
var el = document.querySelector('input.number');
el.addEventListener('keyup', function (event) {
if (event.which >= 37 && event.which <= 40) return;
this.value = this.value.replace(/\D/g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
});
<input class="number">

aboutaaron
- 4,869
- 3
- 36
- 30
-
i can only enter 4 digit here , any specific reason , because i will have more then 4 digit, thanks – parlad Jul 19 '17 at 06:50
-
2
0
<script>
function costt() {
var costs = document.getElementById('cost').value;
if(costs != '') {
// alert("ok");
cost.value = cost.value.replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} else {
// alert("lol");
cost.value= 0;
}
}
</script>

Jhomar
- 1