Recently I came across a problem with a numeric input field. For globalization issues a decimal had to be separated by a comma instead of a dot. So there were 2 solutions in this case. I could prevent users from typing in the dot, or I could replace the dot by a comma when typed. I went for the second one, because on the numeric keypad you only have a dot. So this way it would be easier for the users to input the decimal. It also works the same as applications like Excel who change the dot to a comma to if your regional settings are set that way.
At first sight this looked like an easy chore. In most cases the keypress or keydown event gets handled and the keyCode of the dot gets blocked. Instead the comma is added at the end of the current value of the input field.
In most cases this will do, but when users start editing the decimal, troubles arrive. When the user types a dot inside the number, the comma will be added at the end of the number. But this isn’t what the user wants. He wants to have the comma placed on the location where he type the dot. After some googling, I found the following solution:
What we do is use the provided functionalities in the browsers for detecting selections in an input field. If no text is selected, the range will return the location of the cursor inside the input field. This way we can provide the correct implementation. So even when text is selected and the dot key is pressed, the selected text will be replaced by the comma.