Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ยิง Event เมื่อกด Enter ใน Text Input ด้วย HTML/jQuery

Bind Custom Event "enterKey" บน Input

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
        $('input').bind('enterKey', function(e) {
            alert('Enter key pressed');
        });
        
        $('input').keyup(function(e) {
            if (e.keyCode == 13) { // 13 = Enter
                $(this).trigger('enterKey');
            }
        });
    });
  </script>
</head>
<body>
  <input type="text" placeholder="พิมพ์แล้วกด Enter">
  <p>กด Enter ในช่องข้อความด้านบน</p>
</body>
</html>

ใช้ e.keyCode === 13 (Deprecated แต่ยังใช้ได้) หรือ e.key === 'Enter' (Modern)