javascript 当<input type="number">包含非数字字符时,用JS获取它的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15627341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value of <input type="number"> with JS when it contains non-numeric characters
提问by captainclam
This jsfiddle demonstrates the following issue.
The simplest example is:
最简单的例子是:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
这会按预期记录 1。然而,这:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
由于值中包含非数字字符,因此只记录一个空字符串 ''。某些设备+浏览器(例如 Chrome)允许您在这些输入中输入非数字字符。
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
这很烦人,因为我想要支持它的设备(例如 iPhone、iPad 数字键盘)的 type="number" 输入。但是我想使用 javascript 来阻止输入脏输入 - 这需要获取 keyup 上的值 - 然后正则表达式替换非数字字符。
It appears jQuery's .val() method gives the same result.
看起来 jQuery 的 .val() 方法给出了相同的结果。
采纳答案by captainclam
This is what I was looking for:
这就是我要找的:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
我知道阻止用户输入可能很烦人,这仍然允许无效输入,例如 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to @int32_t for the suggestion.
然而,在这种情况下,这正是我所需要的。希望它对其他人有用。感谢@int32_t 的建议。
回答by Kornel
You're not supposed to use <input type=number>
for things that are not numbers (in very mathematical sense—it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
你不应该<input type=number>
用于不是数字的东西(在非常数学的意义上 - 它也不适用于电话号码或邮政编码)并且清除该值是故意的。
You can test whether device supports type=number
and attach your fallback only if it doesn't:
您可以测试设备是否支持type=number
并仅在不支持的情况下附加您的回退:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
或者(特别是如果您的号码是邮政编码、序列号等),您可以使用:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.
这也会改变键盘。