javascript验证文本框只能输入数字,用var keyCode = event.keyCode不对...
发布网友
发布时间:2022-05-02 10:35
我来回答
共4个回答
热心网友
时间:2022-05-16 21:10
<input type="input" onkeypress="return '0123456789'.indexOf(String.fromCharCode(event.keyCode))!=-1" />
或
<input type="text" onkeydown="return String.fromCharCode(event.keyCode).match(/^\d$/)!=null" />
阻止文本框输入非数字字符,onkeypress/onkeydown有效,onkeyup无效
热心网友
时间:2022-05-16 22:28
<script>
function setNumValue() {
if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 35 || event.keyCode == 36) {
//
} else {
return false;
}
}
</script>
<input type="text" name="icstart" size="20" maxlength="20" onkeydown="return setNumValue();" class="boxinput" value="1">
热心网友
时间:2022-05-17 00:03
这样就可以避免输入非数字了
<input type="input" onkeyup="this.value=this.value.replace(/[^\d]/g,'');" />追问为啥用onkeydown没效果
追答因为onkeydown按下时,value还没改变
热心网友
时间:2022-05-17 01:54
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>输入框只能输入数字</title>
</head>
<body>
<input type="text" name="num" id="num" onkeypress="return keypress(event)">
<script type="text/javascript">
function keypress(e){
e = e ? e : window.event ? event : null;
var keyNum = event.keyCode;
var keyChar = String.fromCharCode(keyNum);
var regDig = /\d/g;
if(regDig.test(keyChar) || keyChar == ""){
return true;
}
var regDot = /\./g;
if (regDot.test(keyChar) && !regDot.test(document.getElementById("num").value)){
return true;
}
return false;
}
</script>
</body>
</html>
参考资料:易科技 http://www.e8it.net