JavaScript学习笔记6--阻止向文本框输入指定的字符

来源:互联网 发布:ubuntu 重置网络 编辑:程序博客网 时间:2024/06/06 04:47
我们给文本框指定一个新的属性invalidchars,凡是在invalidchars里的字符,都是不允许
输入的,怎样实现这个功能呢?看下面的例子:
<html>
  
<head>
    
<title>阻止向文本框输入特定的字符</title>
    
<script type="text/javascript">
    
function blockChars(oTextbox,oEvent){
    
var sInvalidChars=oTextbox.getAttribute("invalidchars");
    
if(oEvent.keyCode){//在IE环境下
     var sChar=String.fromCharCode(oEvent.keyCode);
    }
    
else{//非IE下
    var sChar=String.fromCharCode(oEvent.charCode);
    }
    
var bIsValidChar=sInvalidChars.indexOf(sChar)==-1;
    
return bIsValidChar;
    }
    
    
</script>
  
</head>
  
<body>
    
<form name="f1" id="f1" action="" method="post">
      
<table border="0">
        
<tr>
          
<td>Login:</td>
          
<td><input type="text" name="login" id="login" invalidchars="0123456789" 
               onkeypress
="return blockChars(this,event)" />
          
</td>
        
</tr>
        
<tr>
          
<td>Password:</td>
          
<td><input type="password" name="password" id="password" 
          invalidchars
="abcdefghijklmnopqrstuvwxyz" 
          onkeypress
="return blockChars(this,event)" />
          
</td>
        
</tr> 
        
<tr>
          
<td colspan="2" align="center"><input type="submit" /></td>
        
</tr>
      
</table>
    
</form>
  
</body>
</html>

 

上面的例子里,第一个文本框我们指定invalidchars的值为"0123456789",这样所有的数字
都会被阻止输入进去,第二个文本框里所有的小写字母都不允许输入进去。这里通过
blockChars来实现这个功能,blockChars函数有两个参数,第一个参数oTextbox引用文本框
对象,第二个参数是当前发生的事件对象,keypress事件属于键盘事件,当发生键盘事件时,
我们能够通过事件对象的keyCode属性(For IE)或者charCode属性(其他浏览器)获取当前按
键的Unicode值,然后可以通过String.fromCharCode()方法把Unicode值转化为对应的字符。
通过oTextbox的getAttribute()方法获取属性invalidchars的值,然后看当前按下的键盘键
值是否被包括在invalidchars的值里面,如果在,返回false,阻止字符的输入。否则,返回
true,允许输入。