Reputation: 3207
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
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
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
}
};
Upvotes: 0
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