有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
上面的一些答案使用了过时的内容,比如which的使用。
要检查按下的键是否为数字,可以使用keyup eventListener来读取event.key的值。如果不是数字,就不要输入字符。您可以将其他密钥加入白名单。例如,允许用户使用箭头在输入字段中向后或向前导航,或者按退格键并删除输入的数字。
validate (event) {
const isNumber = isFinite(event.key)
const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
const whitelistKey = whitelist.includes(event.key)
if (!isNumber && !whitelistKey) {
event.preventDefault()
}
}
其他回答
希望我不是用一个丑陋的棍子在这里打死马,但我用这个为我的网站数量输入,它只允许从1到99的数字。
试一试: https://jsfiddle.net/83va5sb9/
<input min="1" type="text" id="quantity" name="quantity" value="1"
onKeyUp="numbersonly()">
<script>
function numbersonly() {
var str = document.getElementById("quantity").value
var newstr = ""
for (i = 0; i < str.length; i++) {
for (ii = 1; ii < 10; ii++) {
if (str.charAt(i).indexOf(ii) > -1) {
newstr += str.charAt(i)
}
}
}
if (newstr == "") {
newstr = 1
}
if (parseInt(newstr) > 99) {
newstr = 99
}
document.getElementById("quantity").value = newstr
}
</script>
你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
然而,你需要绑定到事件,如keyup等。
请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。
只是使用jQuery的另一个变体
$(".numeric").keypress(function() {
return (/\d/.test(String.fromCharCode(event.which) ))
});
//在JavaScript函数中(可以使用HTML或PHP)。
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
在您的表单输入:
<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>
输入max。(以上这些允许使用12位数字)