0

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

let input = document.getElementById('input');
    //add event listener to keydown event    
    input.addEventListener('keydown',(e)=> {
        console.log(e.key);
      //check the key is 'Escape'
        if( e.key === 'Escape') {
            input.select();} 
        });

when I press 'Esc', it didn't work it only blur, don't select what I type in the input element. Where did I make mistake?

jack petton
  • 49
  • 1
  • 10
  • 3
    Possible duplicate of [How to handle ESC keydown on javascript popup window](https://stackoverflow.com/questions/1481626/how-to-handle-esc-keydown-on-javascript-popup-window) – ProllyGeek Dec 13 '18 at 05:34

2 Answers2

0

for pure js

   document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert('Esc key pressed.');
    }
};

for jquery

jQuery(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       alert('Esc key pressed.');
    }
});
Rubin bhandari
  • 1,873
  • 15
  • 20
-1

Your code is running fine. Check it on JS Bin.

Devesh
  • 170
  • 11