Allow special characters / fractions in HTML5 numb

2019-08-04 06:44发布

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.

标签: html html5
2条回答
相关推荐>>
2楼-- · 2019-08-04 06:56

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).

查看更多
再贱就再见
3楼-- · 2019-08-04 07:15

We recently ran into the same issue.

Our goals were ...

  1. Allow users to enter fractions, decimals, and integers on all devices
  2. Display the numeric keyboard on mobile devices

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:

var elmInput = document.getElementById("elmID");
if (/(iPad|iPhone|iPod|Android)/g.test(navigator.userAgent)) {
    elmInput.setAttribute("type", "number");
    elmInput.focus();    // brings up numeric keyboard
    setTimeout(function () {elmInput.setAttribute("type", "text"); }, 200);
}

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 to text when focused.

查看更多
登录 后发表回答