jQuery实现只允许输入数字和小数点的方法
本文实例讲述了jQuery实现只允许输入数字和小数点的方法。分享给大家供大家参考,具体如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<scriptsrc="jquery.min.js"type="text/javascript"></script>
<scripttype="text/javascript">
//示例代码:
//只允许输入数字与.:<inputtype="text"name="test"id="test"onkeydown="checkKeyForFloat(this.value,event)"style="ime-mode:disabled"/>
//只允许输入数字:<inputtype="text"name="test2"id="test2"onkeydown="checkKeyForNum(this.value,event)"style="ime-mode:disabled"/>
//只允许输入数字与小数点
functioncheckKeyForFloat(value,e){
varisOK=false;
varkey=window.event?e.keyCode:e.which;
if((key>95&&key<106)||//小键盘上的0到9
(key>47&&key<60)||//大键盘上的0到9
(key==110&&value.indexOf(".")<0)||//小键盘上的.而且以前没有输入.
(key==190&&value.indexOf(".")<0)||//大键盘上的.而且以前没有输入.
key==8||key==9||key==46||key==37||key==39//不影响正常编辑键的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)
){
isOK=true;
}else{
if(window.event)//IE
{
e.returnValue=false;//event.returnValue=false效果相同.
}
else//Firefox
{
e.preventDefault();
}
}
returnisOK;
}
//只允许输入数字
functioncheckKeyForInt(value,e){
varisOK=false;
varkey=window.event?e.keyCode:e.which;
if((key>95&&key<106)||//小键盘上的0到9
(key>47&&key<60)||//大键盘上的0到9
key==8||key==9||key==46||key==37||key==39//不影响正常编辑键的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)
){
isOK=true;
}else{
if(window.event)//IE
{
e.returnValue=false;//event.returnValue=false效果相同.
}
else//Firefox
{
e.preventDefault();
}
}
returnisOK;
}
//设置有自定义属性dtype的文本框允许输入的范围
functionsetDType(){
$(":text[dtype]").each(function(){
vardtype=$(this).attr("dtype");
varisOK=true;
switch(dtype){
case"number":
$(this).css("ime-mode","disabled").keydown(function(event){
isOK=checkKeyForFloat($(this).val(),event);
if(!isOK){
//$(this).SuperFocus("",500);
}
returnisOK;
});
break;
default:
break;
}
});
}
</script>
<scripttype="text/javascript">
$(function(){
setDType();
});
</script>
</head>
<body>
年龄:<inputtype="text"maxlength="3"onkeydown="checkKeyForInt(this.value,event)"style="ime-mode:disabled"/><br/>
身高:<inputtype="text"maxlength="5"dtype="number"/>
</body>
</html>
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery拖拽特效与技巧总结》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》、《jquery选择器用法总结》及《jQuery常用插件及用法总结》
希望本文所述对大家jQuery程序设计有所帮助。