Mobile-friendly input of a digits + spaces string (a credit card number)

我的未来我决定 提交于 2019-11-30 20:17:35

The semantically correct markup for a text field that can still contain whitespace and other special characters is <input type="text" inputmode="numeric"/> however as far as I am aware while inputmode is recommended by WhatWG it is not yet supported by any browsers. Its intent is to present the user with a numeric keypad on a device that has it but still behave as a text input.

My suggestion would be to polyfill inputmode with JS and change to type="tel" on touch devices (which is the best solution currently available). Be mindful that differently devices have very different 'tel' and 'number' keypads, iOS 'tel' does not allow spaces while Chrome mobile allows all sorts of special characters. Who knows what custom Android keypads do?

If you don't want to build your own polyfill you can implement Webshim which now polyfills inputmode as of release 1.14.0. This also has has the nice feature of keeping the iOS 'number' keypad invoked by setting pattern="[0-9]*" if you want it (note: this is not the same keypad you get when setting type="number"!)

Here is the analysis I did on input type behavior across browsers and my debate with @aFarkas (the Webshim author) on polyfilling inputmode.

From what I know there is no keyboard layout on the iPhone that allows both numbers and space without at least automatically switching back from numbers to characters. Typing a number with spaces in between will require the user to repeatedly switch back to the numbers keyboard layout after each space.

If you would offer individual input fields for the four blocks of numbers and use some javascript to automatically move over the cursor from one input field to the next once the fourth number has been typed, you could use <input type="number"/> plus you would spare iPhone users from switching between keyboard layouts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!