0

I am trying to add a keylistener to my input field but I can't make it work. My input type is text with id= "code". Here is what I tried:

document.querySelector('code').addEventListener('keypress', function (e) {
    var key = e.which || e.keyCode;
    window.alert(key);
});

and

document.getElementById('code').addEventListener("keydown", dealWithKeyboard, false);

function dealWithKeyboard(e) {
    if (window.event) { // IE
        keynum = e.keyCode;
    } else if (e.which) { // Netscape/Firefox/Opera
        keynum = e.which;
    }
    window.alert(keynum);
}

and

document.getElementById('code').onkeyup = function(e) {
    if (window.event) { // IE
        keynum = e.keyCode;
    } else if (e.which) { // Netscape/Firefox/Opera
        keynum = e.which;
    }
    window.alert(keynum);
}

But none seems to work

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Ann
  • 377
  • 5
  • 16

1 Answers1

3

You aren't using the proper selector with document.querySelector(). An id value must be preceded by # as in document.querySelector('#code').

document.querySelector('#code').addEventListener('keypress', function (e) {
    var key = e.which || e.keyCode;
    console.log(key);
});

Working snippet:

document.querySelector('#code').addEventListener('keypress', function (e) {
  var key = e.which || e.keyCode;
  log(key);
});

// show output
function log(x) {
  var div = document.createElement("div");
  div.innerHTML = x;
  document.body.appendChild(div);
}
Type some characters in the Input field here: 
<input id="code">

Implemented properly, your document.getElementById('code') example should work.


If this still doesn't work, then check for two more things:

  1. Make sure that you are executing this script AFTER the relevant parts of the DOM have been loaded. There are several ways to assure this, but the simplest is to just located the <script> tag after the HTML that it refers to.

  2. Make sure that there are no script errors that are preventing your code from executing. You can check the debug console to check for errors.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @Ann - Then perhaps you are attempting to run your code too early BEFORE the DOM has loaded. Make sure the script is in a ` – jfriend00 Mar 06 '16 at 10:31
  • @Ann - Another possibility is that you have a script error that is preventing your code from executing. You would have to check the debug console to see if you have any such script errors. As you can see in the snippet above, the concept works just fine when implemented properly. – jfriend00 Mar 06 '16 at 10:33