I have an html5 number input: <input type="number" />
I would like it to accept fractions and mixed numbers, such as 38 1/2 as well as whole numbers and decimals.
I parse the fractions server side.
Currently, when the input loses focus, the browser changes the input to 38.
A current workaround is using a plain text input, but I would like the benefits of using type="number"
such as specific keyboards on mobile.
The
<input type="number">
element is defined to create a browser-dependent browser-locale-dependent input control for entering numbers. There is no way to change this in your document, except in the sense that you can use attributes to specify the range and precision. So a browser could accept 38 1/2 and convert it internally to 38.5, but there is no way to say that it should, still less force it to do so. Moreover, the internal format of the numbers (as passed to the server) is defined strictly; it cannot be 38 1/2 for example.So you need to use plain text input or some special widget (programmed in JavaScript). You can use the
pattern
attribute to specify the allowed format somehow, at least the allowed set of characters; this may or may not affect the on-screen keyboard displayed on touch devices (it probably won’t, for current devices).We recently ran into the same issue.
Our goals were ...
If we simply used
type='number'
, most desktop browsers would prevent us from entering the slash character. In mobile Safari, we were able to enter a slash (e.g., 2/3), but the browser converted the value to an empty string since it wasn't strictly numeric.Our solution has been to temporarily change the input type to
number
for devices that we want to display the numeric keyboard.Our solution looks like:
We have tested on several iOS devices, and we are seeing the intended behavior. Obviously, this solution is limited to these devices. Also, in the unlikely event that the user submits the form in less than 200 milliseconds, he will run into the empty string problem previously mentioned.
Our situation is obviously unique since we're only dealing with one element that we can trigger focus. However, a similar approach could work by using a CSS class selector. You could set type to
number
for mobile devices, and then change back totext
when focused.