Shlomi Schwartz Shlomi Schwartz - 1 year ago 110
Javascript Question

JS - Map alphanumeric keyboard keyCode to a dial pad number 2 - 9

I'm trying to create a dialer widget, catch "keydown" event and highlight the corresponding dialer number.

So, for example clicking "A" on the keyboard, would highlight "2" on the UI:

dialer HTML UI

I've managed to map the first 5 digits (2-6). Since they contain 3 letters each, I was able to map the keyCode like so:

Math.floor(((KeyCode - 65) / 3) + 2).

Q: Is there a way to do it in one line, so PQRS and WXYZ would fit the solution?

Answer Source

If you really need it, that might work:

    Math.min(9, Math.floor(((KeyCode - (KeyCode < 83 ? 65 : 66)) / 3) + 2))

but you also have to make sure that KeyCode actually is a letter.

The obvious solution you discussed is way better, because it's readable, configurable, and peforms equally fast:

    function toDialNumber(KeyCode) {
      var keyMap = {1:"", 2:"ABC", 3:"DEF", 4:"GHI", 5:"JKL", 6:"MNO", 7:"PQRS", 8:"TUV", 9:"WXYZ"};
      var letter = String.fromCharCode(KeyCode);
      for(key in keyMap) if(keyMap[key].indexOf(letter)>=0) return key;
      return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download