代码如下,需要引入外部jquery文件,本例为Jquery-1.4.2.min.js。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>限制用户只能输入数字-www.jb200.com</title>
<body>
<input type="text" id="txt1">
</body>
<script src="/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.fn.numeral = function(){
$(this).css("ime-mode","disabled");
this.bind("keypress",function(event){
var keyCode = 0;
if (event.charCode != undefined) {
keyCode = event.charCode;
} else {
keyCode = event.keyCode;
}
if(keyCode == 46){
if(this.value.indexOf(".")!=-1){
return false;
}
}else{
return (keyCode>=46&&keyCode<=57) || (keyCode==0);
}
});
this.bind("blur",function(){
if(this.value.lastIndexOf(".")==(this.value.length-1)){
this.value = this.value.substr(0,this.value.length-1);
}else if(isNaN(this.value)){
this.value = "";
}
});
this.bind("paste",function(){
var s=clipboardData.getData('text');
if(!/D/.test(s));
value=s.replace(/^0*/,'');
return false;
});
this.bind("dragenter",function(){
return false;
});
this.bind("keyup",function(){
if(/(^0+)/.test(this.value))this.value=this.value.replace(/^0*/, '');
});
};
$("#txt1").numeral();
</script>
</html>