user1167650
user1167650

Reputation: 3207

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?

Upvotes: 7

Views: 7456

Answers (4)

naspinski
naspinski

Reputation: 34689

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

Upvotes: 3

jbabey
jbabey

Reputation: 46647

Use the keypress event in combination with String.fromCharCode:

document.getElementById('yourTextBoxID').onkeypress = function () {
    var characterPressed = String.fromCharCode(event.keyCode);

    if (characterPressed.test(/[a-z]/i)) {
        // user pressed a letter
    } else {
        // user did not press a letter
    }
};​

http://jsfiddle.net/TSB9r/3/

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

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

Upvotes: 7

Explosion Pills
Explosion Pills

Reputation: 191749

Use keydown instead of keyup.

Upvotes: 1

Related Questions