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.
+2
A:
Something like this should work:
$(document).ready(function(){
$('input.number').keyup(function(){
var $this = $(this);
var num = $this.val().replace(/,/g, '');
// the following line has been simplified. Revision history contains original.
$this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
});
});
Edit: Tested. This works.
macek
2010-04-13 19:18:05
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
2010-04-13 20:45:35
@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.
macek
2010-04-13 20:48:12