Is there a quick way to set an HTML text input (<input type=text />
) to only allow numeric keystrokes (plus '.')?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
You can also compare input value (which is treated as string by default) to itself forced as numeric, like:
However, you need to bind that to event like keyup etc.
I've searched long and hard for a good answer to this, and we desperately need
<input type="number"
, but short of that, these 2 are the most concise ways I could come up with:If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!
JavaScript code:
HTML code:
works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)
Use this DOM:
And this script:
...OR this script, without indexOf, using two
for
's...I used the onkeydown attribute instead of onkeypress, because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the Google Chrome browser.
With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!
ASCII Code for TAB => 9
The first script have less code than the second, however, the array of ASCII characters must have all the keys.
The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:
NCount = 0
48 + NCount = 48
NCount + +
48 + NCount = 49
NCount + +
...
48 + NCount = 57
In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.
ASCII codes:
If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use
<input type="number">
.This is an improved function: