Javascript - Intercepting keystrokes

I have an input field that always has focus. Commands that enter this input field are always letters. If the user clicks the number, I would like it to not be added to the text box, but instead use it to run another command (like a hotkey).

The way I saw this is to look at the keyup event and remove the unnecessary characters. Instead, is there a way to intercept keyboard input and verify that this value is before pasting?

I thought about creating a custom input field using a div and intercepting all keyboard commands. Is there any way to get the flashing carriages so that it looks like an input field?

+4
source share
4 answers

It looks like you want a contenteditable div:

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

You can listen for keydown events and prevent them if they are not letters:

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

To treat numbers like hotkeys, you simply determine which e.which key works accordingly.

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

+5
source

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

+1
source

Use keydown instead of keyup .

0
source

Use the keypress event in conjunction with String.fromCharCode :

 document.getElementById('yourTextBoxID').onkeypress = function () { var characterPressed = String.fromCharCode(event.keyCode); if (characterPressed.test(/[az]/i)) { // user pressed a letter } else { // user did not press a letter } };​ 

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

0
source

All Articles