How do I format the number as I type it in the html input box?
so for example, I want to type the number 2000, the moment I type the 4th digit, the text (that's currently displayed in the textbox) will be automatically formatted to 2,000 (with a comma).
//my modified code based on Moob answer below
<input type="text" class="formattedNumberField" onkeyup="myFunc()">
//jQuery
$(".formattedNumberField").on('keyup', function(){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
});
function myFunc(){
// doing something else
}
while this code works perfect as shown in Moob Fiddle, its not working on my end maybe because I have another onkeyup event inside the inputbox???
Based on the example you've given, you can use something like this:
I used jQuery in the above, but it can be done with pure JS also.
Working example here
You can use ngx-format-field. It is a directive to format the input value which will appear in the view. It will not manipulate the Input value which will be saved in the backend. See link here!
Example:
To see the demo: here!
Try this plugin it works pretty nice http://robinherbots.github.io/jquery.inputmask/
With some code bits of other answers I created the following working example. Code is without jquery, but a little bit longer than some other examples. But it takes care of a lot of the problems that others have.
http://jsfiddle.net/kcz4a2ca/10/
Code:
Pure JS (Sans jQuery):
Native JS Example Fiddle
With jQuery:
With jQuery Example Fiddle
To allow decimals:
Obligatory Example