2017-05-08 65 views
0

我希望能夠得到用戶的輸入,以驗證它,看看它是否是我想出現或使用的密鑰。我不想要輸入內容的全部價值,只是他們輸入的特定鍵。Jquery:我如何獲得用戶的輸入,因爲他們鍵入

我已經在Javascript中使用此代碼完成了它,但它在Jquery中不起作用。謝謝!

<input type="text" id="a"> 

$("#a").on('input', function(e){ 
    var charval = String.fromCharCode(e.Keycode); 
    alert(charval); 
}); 

警報應該顯示被按下的鍵。

DEMO:

$("#a").on('input', function(e){ 
 
\t var charval = String.fromCharCode(e.Keycode); 
 
\t alert(charval); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="a">

+0

檢查https://jsfiddle.net/qm7zka87/ 2/ –

+0

它顯示了什麼?這似乎是我的錯字。 –

+0

輸入事件也無法訪問被按下的鍵。 –

回答

0

考慮一下:

document.getElementById('f').addEventListener('keyup', function(e) { 
 
    document.getElementById('out').textContent = e.keyCode; 
 
})
<input type="text" id="f"> 
 
<p id="out">Hi</p>

你會看到最後一次按下按鈕鍵碼。如果您願意,您還可以在偵聽器中添加警報。

0

變化e.keycode到e.which

$("#a").on("keypress", function(e){ 
 
var charval = String.fromCharCode(e.which); 
 
    alert(charval); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="a">

0

就固定你的代碼工作:

$("#a").on('keyup', function(e){ 
     var charval = String.fromCharCode(e.which); 
     alert(charval); 
}); 
相關問題