I’m trying to write a jQuery plugin to prevent users from typing numbers with more than 2 decimal places. Specifically:
- If an input contains
12and the user types3at the end, it should work. - If an input contains
12.34and the user types1at the end, nothing should happen. - If an input contains
12.34and the user types1at the beginning, it should work.
Here’s the problem I’m running into:
- If I bind to
keypress, I do not know what the “proposed new value” is;$(this).val()is the value before the user pressed the key, and I don’t know where in the input field the user is typing. - If I bind to
keyup,$(this).val()is the new value, but it has already appeared in the text input. I can erase it if it has too many decimal places, but it looks glitchy.
How can I do this?
Mebbe this?
Tested and working at http://jsfiddle.net/vdZfH/2/