← Back to Upcase

JavaScript Input Formatting

(Edward Loveall) #1

Any suggestions on what to use for JavaScript input formatting? Currently, I’m looking for something that will do prices, i.e. turn 12345 into $123.45. It’d be great to have something more extendable so I could also have 12345 turn into 1/23/45 or a different format.

Any suggestions?

(Joel Quenneville) #2

This library looks like it will do what you are asking: http://numeraljs.com/

(Edward Loveall) #3

This looks really slick. Unfortunately it doesn’t seem to do the formatting live. I neglected to mention that. I’m trying it for now because it does seem wonderfully clean.

(Sean Griffin) #4

@edwardloveall , can you elaborate on what you mean by doing it live?

(Edward Loveall) #5

When you type in a field, I’d love it to restrict and correct what you can type. For example if you try to type letters in a phone number, they don’t show up. If you start typing number in a price, it starts filling out the cents, puts a period after two numbers, and prepends a $ sign.

This plugin is actually pretty close, but doesn’t allow for formats that have a variable number of characters on the front end. Here’s a decent live example. I’m not sure this allows for flexible length either: http://firstopinion.github.io/formatter.js/demos.html

(Sean Griffin) #6

That’s something that would be fairly simple to adapt with any library.

$(".my-input").on("keyup", function() {

(Edward Loveall) #7

Ah ok, let me be a little more clear. The box that you’re typing into would be the one that’s being auto-formatted. I was an apprentice on a project with @harlow where he accomplished this. I wonder if he might be able to chime in?

What I ended up doing for now was:


(Joel Quenneville) #8

Are you looking for something more like this? http://robinherbots.github.io/jquery.inputmask/

(Edward Loveall) #9

That works pretty well @joelq, thanks! For those wondering, I got it working relatively well with the RegEx extension and this mask:

$(selector).inputmask('Regex', {regex: "[0-9]+\\.[0-9]{2}"})

The only caveat is I couldn’t figure out how to get a $ sign in front of the price. A label will work just fine though.