Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers dynamically in input field?

I'd like to format a number on the fly as user types. There are a couple of usefull plugins like jquery.maskedinput, but none of them is able to create a dynamic mask that would work with all of scenarios:

  • 1000000 -> 1 000 000
  • 100000 -> 100 000
  • 10000 -> 10 000

And so on. Perhaps there is a clever way to achieve this with jquery dynamically as user types? Or maybe I just missed one plugin that does this? :)

like image 565
pielgrzym Avatar asked Jun 24 '11 13:06

pielgrzym


2 Answers

There's a nice plugin that can both format and parse numbers like this. jquery-numberformatter

What you would want to do is when the value of the field changes, immediately parse the field value, and set it back into the format you desire.

like image 188
hughes Avatar answered Oct 06 '22 13:10

hughes


Here is a nice regexp to take the string apart properly: javascript split string at parts

And here is a small experimental plugin that seems to work ok now (thanks to Segaja from #jquery on freenode!):

https://gist.github.com/1047003

To use it just include it in the page code and add:

$("input.someclass").formatInput();
like image 37
pielgrzym Avatar answered Oct 06 '22 14:10

pielgrzym