2016-04-15 43 views
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> 
+0

這是一個演示?我沒有看到有疑問或問題,要麼?謝謝你的演示伴侶.. :) – guradio

+0

'如果(X!= '0' || X! ='1'){'這是有意添加與否? – Bhumika107

+0

@ Developer107,這個條件會在不匹配時刪除。 –

回答

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

+0

這個答案不完全正確,因爲它接受「!」 &「)」符號作爲輸入。請更新您的代碼.. –

+0

@ Prakash Thete,你是對的。 –

+0

@Xzandro,數字0到7的條件是什麼? –

0

我會使用一個正則表達式來代替一切,是不是0或1

<body> 
    <input id="whichkey" /> 
    <script> 
     $("#whichkey").on("keydown", function(event) { 
     $(this).val($(this).val().replace(/[^01]/g, '')); 
     } 
     }); 
    </script> 
</body> 
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> 
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> 
+0

你可以縮短這段代碼嗎,非常冗長。 –

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> 
+0

對你來說足夠了嗎? – Tosif