在按键不匹配时删除输入字符

时间:2016-04-15 03:29:21

标签: javascript jquery

  

为什么这种情况不起作用?

     

用户只能输入' 0' 0和' 1'否则就不应该输入。

<body> 
    <input id="whichkey" />
    <script>
      $( "#whichkey" ).on( "keydown", function( event ) {
        var x = event.which;   
        if(x !== '0' || x !== '1'){
            var userAns = $("#whichkey").val(),     
            shortString = userAns.substr(0,(userAns.length -1));
            $('#whichkey').val(shortString);
        }
      });
    </script> 
</body>

5 个答案:

答案 0 :(得分:0)

也许你可以试试这个

$( "#whichkey" ).on( "keydown", function( event ) {
    var x = event.which;  
    console.log(x)
    if(x !== 48 && x !== 49 && x !== 96 && x !== 97){
        return false;
    }
});

Fiddle

答案 1 :(得分:0)

我会使用正则表达式来替换不是0或1

的所有内容
<body> 
    <input id="whichkey" />
    <script>
      $( "#whichkey" ).on( "keydown", function( event ) {
        $(this).val($(this).val().replace(/[^01]/g, ''));
        }
      });
    </script> 
</body>

答案 2 :(得分:0)

有类似的东西!?

<body> 
    <input id="whichkey" />
    <script>
      $( "#whichkey" ).on( "keydown", function( event ) {
        var x = event.which;   
        if(x !== 48 && x !== 49 && x !== 96 && x !== 97) $('#whichkey').val(null);
      });
    </script> 
</body>

答案 3 :(得分:0)

 <body>
 <input id="whichkey" onKeyDown="test(event,this.id)"/> 
  press enter key after inputting string
<script>
function test(e,id)
{
    if(e.keyCode==13 || e==13)
    {
         var userAns = $('#'+id).val();
         var shortString =userAns.substr(0,1)
        if(shortString==1 || shortString==0)
        {
            $('#whichkey').val(shortString);
        }
        else
        {
            alert("Only 0 & 1 is allowed");
            $('#whichkey').val("");

        }
    }

}

</script> 
</body>

答案 4 :(得分:0)

<body>
<input id="whichkey"/> press enter key after inputting string
  <script>
$("#whichkey").on("keydown",function(e){test(e,this.id)});
function test(e,id)
{ 
    if(e.keyCode==13){
         var userAns = $('#'+id).val();
         var shortString=userAns.substr(0,1);
         (shortString==1)? shortString:shortString="";
            $('#whichkey').val(shortString);
        }
     }

  </script> 
</body>