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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With