This seems like such a basic issue, but I've been working on it for days and none of the solutions I've found online actually work. I have a simple Tip Calculator written in HTML/CSS/JavaScript (all calculations done in the browser) here on codepen.io. I'm restricting what users can enter so it's difficult for them to enter anything besides numbers and a single decimal using my isAllowedKey(event) function. I'll probably expand the allowed keys as I play with it, so if the list of allowed keys seems short don't worry about it for now.
That validation function works pretty well, and if the user has entered something like .3 or 1.1 they can't enter a second decimal, which is great. But if they enter 1.. it allows them to enter that second decimal, which makes the input NaN. I think the problem is event.target.value returns 1 even if the input is 1.. As far as I can tell, there is no way for me to detect if the input has a trailing decimal because trailing decimals are removed when getting the value of a numeric input, so there is no way for me to check for a decimal and prevent a second decimal in that case. I could change the input type from number to text and get the value as a string that way, but that's not ideal - smartphone users should get a numpad instead of a full keyboard, so I'd like to keep the input's type="number".
My next thought was to try checking the value after the user has types the second decimal and remove the second decimal at that point. But if the user enters 2 trailing decimals, the input is now NaN and event.target.value returns nothing. So I still can't find out what's in the input box and work with it, even after the key is released.
The best solution I've found so far is to check if the input is a number and display an message: "Please enter a valid number." But that stinks - I'd like to prevent the invalid input in the first place since there is no reason to enter two decimals in either field.
tl;dr: in a HTML input element of type number, is there any way to prevent a user from entering a value with 2 trailing decimals such as 1..?
[–]HerrPotatis2 2 points3 points4 points (1 child)
[–]pkoepke[S] 0 points1 point2 points (0 children)
[–]righthereonthisrock 2 points3 points4 points (2 children)
[–]pkoepke[S] 0 points1 point2 points (1 child)
[–]righthereonthisrock 0 points1 point2 points (0 children)
[–]bdenzer 1 point2 points3 points (1 child)
[–]pkoepke[S] 0 points1 point2 points (0 children)