jQuery keypressメソッドを使ってキーが押されたイベントを取得する

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
$('要素を指定’).on('keypress’, function() {処理コード
「on」メソッドで「keypress」を指定してキーが押されたイベントを取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
$('#txt').on('keypress', function (e) {
$('#result').text(e.which)
})
})
</script>
</head>
<body>
<h2 id="result"></h2>
<input id="txt" type="text">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function () { $('#txt').on('keypress', function (e) { $('#result').text(e.which) }) }) </script> </head> <body> <h2 id="result"></h2> <input id="txt" type="text"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
    $('#txt').on('keypress', function (e) {
      $('#result').text(e.which)
   })
})
</script>
</head>
<body>
  <h2 id="result"></h2>
 <input id="txt" type="text">

</body>
</html>

実行結果
テキストフォーム上で「a」と入力すると、キーコード「97」が表示されます。

jQuery

Posted by arkgame