Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript -- Intercepting keyboard presses

I have an input box that always has focus. The commands that go into this input box are always letters. If the user presses a number, I would like it not to be added to the text box , but instead use it to run a different command (just like a hotkey).

The way I've seen this implemented is by looking at the keyup event and removing unwanted characters. Instead, is there any way to to intercept the keyboard input and check what the value is before the insert?

I've thought about creating a custom input field using a div and intercepting all the keyboard commands. Is there a way to get a blinking caret so that it looks like an input box?

like image 826
user1167650 Avatar asked Aug 17 '12 17:08

user1167650


2 Answers

Sounds like you want a contenteditable div:

<div id="editor" contenteditable="true"></div>

You can listen for keydown events and prevent them if they aren't letters:

$("#editor").keydown(function (e) {
    if (e.which > 90 || (e.which > 48 && e.which < 65)) {
        e.preventDefault();
    }
});

To process the numbers as "hotkeys" you would just determine which key e.which is and act accordingly.

Example: http://jsfiddle.net/g3mgR/1

like image 119
Andrew Whitaker Avatar answered Oct 16 '22 19:10

Andrew Whitaker


Something like this will work:

<input type="text" id="txt" />​

For jQuery:

$('#txt').keydown(function (e) {
    var key = e.charCode || e.keyCode || 0;
    if (key > 46 && key < 58) {
        event.preventDefault();
        alert('its a number, do something');
    }
});​

Here is the Fiddle

like image 22
naspinski Avatar answered Oct 16 '22 19:10

naspinski