JS控制键盘输入

时间:2021-06-27 00:32:17

<html>
 <head>
  <script>
   /* Author: Kevin
   *  Date: 2011-10-21
   *  Description: 
   *   1. 'num': Only allow to input number 0-9;
   *   2. 'alp': Only allow to input alphabet A-Z(a-z);
   *   3. 'numalp': Only allow to input both number and alphabet above.
   */
   function fnInputCondition(pKind){
    
    var code = event.keyCode;
    var invalid = false;
    var invalidMsg = "";
    pKind = pKind.toUpperCase();
    //alert("Kevin test: code = " + code);
    if(!fnCheckControl()){
     
     if(pKind == "NUM"){
      if(!fnCheckNum()){
       invalid = true;
       invalidMsg = "只能输入数字!";
      }
     }else if(pKind == "ALP"){
      if(!fnCheckAlphabet()){
       invalid = true;
       invalidMsg = "只能输入英文字母!";
      }
     }else if(pKind == "NUMALP"){
      if(!(fnCheckNum() || fnCheckAlphabet())){
       invalid = true;
       invalidMsg = "只能输入数字和英文字母!";
      }
     } 
     if(invalid){
      event.returnValue = false;
      alert(invalidMsg);
     }
    }
    // 检查是否输入控制键
    function fnCheckControl(){
     // 8对应退格键, 46对应Del键, 37对应向左键, 38对应向上键,39对应向右键, 40对应向下键
     // 13对应回车键,20对应大写锁定键, 16对应Shift键, 144对应数码锁定键, 35对应End键,36对应Home键
     if((code == 8 || code == 46 || code == 144 || code == 35 || code == 36 ||
      code == 37 || code == 38 || code == 39 || code == 40 ||
      code == 13 || code == 20 || code == 16)){
      return true;
     }else{
      return false;
     }
    }
    // 检查是否输入数字
    function fnCheckNum(){
     // 48-57对应键盘0-9, 96-105对应小键盘0-9, 并屏蔽Shift+(0-9)组合键
     if (((code>=48 && code<=57) || (code>=96 && code<=105)) && event.shiftKey != true){
      return true;
     }else{
      return false;
     }
    }

    // 检查是否输入字母 
    function fnCheckAlphabet(){
     // 65-90对应A-Z(a-z), 大小写同一个按键
     if ((code>=65 && code<=90)){
      return true;;
     }else{
      return false;
     }
    }
   }
  </script>
 </head>
 <body>
  <input type="text" id="t_inputQty" maxlength=200 onkeydown="fnInputCondition('alp');"/>
 </body>
</html>