Home > Web Front-end > JS Tutorial > Input box filters non-numeric js code_javascript skills

Input box filters non-numeric js code_javascript skills

WBOY
Release: 2016-05-16 16:36:10
Original
1167 people have browsed it

HTML:

Copy code The code is as follows:


JS:

window.onload=function(e){
var text=document.getElementById("only"),pattern=/\d/,//pattern匹配字母上的数字键
pattern2=/(9[6-9])|(10[0-5])|3(7|9)/,//pattern2匹配小键盘上的数字键和左右方向键
EventHandle={},event=e||window.event;//一个处理事件的对象

      //当网页加载的时候,进行判断,对事件处理对象进行定义属性,这样对事件对象的方法只需要进行一次判断,以后的其他事件
      //处理程序里面不需要判断
if(event.preventDefault){
EventHandle.preventDefault=function(e){
e.preventDefault();
};
}else{
EventHandle.preventDefault=function(e){
e.returnValue=false;
}
}
text.onkeydown=function(e){
var event=e||window.event;//不同事件的事件对象不一样,这个event和最前面的event不相等
if(!pattern.test(String.fromCharCode(event.keyCode))&&event.keyCode!=8//keyCode=8是退格键,因为可以对输入的数字进行修改,所以退格和左右方向键不禁止
&&!pattern2.test(event.keyCode.toString())||event.shiftKey||
event.ctrlKey||event.metaKey){
EventHandle.preventDefault(event);//如果不用对象的这个方法,写成下面这样,也可以执行,不过每次按下键盘的时候都会进行一次判断
                               //这个是没有必要的,所以在页面加载的时候对事件处理对象定义一个方法,加载后对象的方法就已经是确定的了,以后时候就可以了

                                //if(event.preventDefault){
                                //event.preventDefault();
                                //}else{
                                //event.returnValue=false;
                                //}
}
}
}

Copy after login

Uncommented version:

window.onload=function(e){
var text=document.getElementById("only"),pattern=/\d/,
pattern2=/(9[6-9])|(10[0-5])|3(7|9)/,
EventHandle={},event=e||window.event;
if(event.preventDefault){
EventHandle.preventDefault=function(e){
e.preventDefault();
};
}else{
EventHandle.preventDefault=function(e){
e.returnValue=false;
}
}
text.onkeydown=function(e){
var event=e||window.event;
if(!pattern.test(String.fromCharCode(event.keyCode))&&event.keyCode!=8
&&!pattern2.test(event.keyCode.toString())||event.shiftKey||
event.ctrlKey||event.metaKey){
EventHandle.preventDefault(event);
}
}
}
Copy after login

In IE11, F12 opens the developer tools and you can select the IE version for debugging

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template