onkeyup="value=value.replace(/[^\d]/g,'')"?

ruanwxh 2009-10-30 10:13:10
<input type="text" name="text" value="0" onkeyup="value=value.replace(/[^\d]/g,'')"/>
怎样让他只能输入整数?例如:禁止输入0123456。
...全文
1203 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
friendly_ 2009-10-30
  • 打赏
  • 举报
回复
按照楼主的原意
<input type="text" name="text" value="0" onkeyup="value=value.replace(/[^\d]/g,'').replace(/^0(\d+)$/,'$1')"/>
BeenZ 2009-10-30
  • 打赏
  • 举报
回复
这样效果好

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
<script>
function regInput(obj, reg, inputStr) {
var docSel = document.selection.createRange()
if (docSel.parentElement().tagName != "INPUT") return false
oSel = docSel.duplicate()
oSel.text = ""
var srcRange = obj.createTextRange()
oSel.setEndPoint("StartToStart", srcRange)
var str = oSel.text + inputStr + srcRange.text.substr(oSel.text.length);
return reg.test(str)
}
</script>
<input type="text" id="txt" onkeypress = "return regInput(this,/^\d*$/,String.fromCharCode(event.keyCode))">



</body>
</html>

  • 打赏
  • 举报
回复
=== 结贴,给分 ===
  • 打赏
  • 举报
回复

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
/**
* author: develop_design_level
* date: 2009-10-30
* @param {Object} id
*/
function $(id){
if (document.getElementById) {
return document.getElementById(id);
}
else {
return document.all.id;
}
}
function checkInputText(){
var regExp = /^\d+$/g;
var text = this.value;
if(!regExp.test(text)){
this.value = '0';
}
}
window.onload = function(){
$('testId').onkeyup = checkInputText;
};
</script>
</head>
<body>
<form>
<input type="text" id="testId" value="0">
</form>
</body>
</html>

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧