Altering the keypress event of certain keys in JavaScript - javascript

I am working on a project which shows the character code of each key that is pressed down inside a text box.
My problem is that when certain keys, namely: Shift, Backspace, Space are pressed down, their character codes appear like: 16, 8, 32.
I want these keys to retain their normal behavior when pressed. So that space causes a space in the text box, and backspace deletes the character, and so on...but the rest of the keys to continue outputting their character code.
How can I go about accomplishing this?

You can just check for the keys and handle accordingly. Here's a demo:
document.getElementById("test-textbox").addEventListener("keypress", function(event) {
var code = event.keyCode || event.which;
if(code === 16 || code === 8 || code === 32) //check if space, shift, or backspace
return; //if yes, allow
console.log(code); //if not, log value
event.preventDefault(); //prevent entry
});
<input type="text" id="test-textbox">
This will allow the shift, backspace, and space keys to be pressed, but all others will be logged.

I think this will work for you.
var elementID = document.getElementById('elementID');
elementID.onkeydown = function(event) {
var key = event.keyCode || event.charCode;
if( key == 32 || key == 8 )
event.preventDefault();
};

As long as you…
don’t call the preventDefault method on the event object, and
don’t return false from the event handler
…you should be fine.
In particular, the handler…
function showCharCode(event) {
// NOTE: Don’t call `event.preventDefault()` here.
document.querySelector('.char-code').textContent = event.charCode;
// NOTE: Don't return false here.
}
… will still propagate the event to the default textbox (or input, or contenteditable) element.

Related

Get the keypress code without to care which symbol is clicked using JQuery

I see here is have few questions when is asking for how can get which key is clicked from keyboard. I tested is ok is working if is in English case.
If I change the language and the symbols on keyboard is changed then is not show anything.
So my question is how can I get the keypress code without to care which language is now used the user when is click the key 'G' or 'Г' or something else.
here is my simple jquery code
$(document).keypress(function(e) {
if (e.charCode == 103) {
alert('g');
} else if (e.charCode == 71) {
alert('G');
}
});
If is with english is working, when I change to Bulgarian then is not working. How can I make to working on every language?
Using the keypress event will give you the character typed, regardless of keyboard layout.
For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charTyped = String.fromCharCode(charCode);
alert("Character typed: " + charTyped);
};
I find the solution of my problem. Thanks of this article
$(document).on('keydown', function(e) {
if (e.ctrlKey) {
alert('Echo');
} else {
alert(e.which + ' ' + e.key);
}
});
What I'm changing. I change only the event. I replace 'keypress' with 'keydown' and now is the same code without to care which language is used.

Binding the "onselect" event to a function, that handles the maximum chars. inside an input text field

I am working on a function to limit the number of chars. a user is allowed to type inside an input text field.
This is it:
$.fn.restringLength = function (id, maxLen) {
$(id).keypress(function(e){
var kCode = e.keyCode ? e.keyCode : e.which,
len = $(id).val().length;
if (kCode != 8 && kCode != 46) {
if (len > maxLen) e.preventDefault();
}
});
}
The function binds the keypress event and gets the code of the pushed key.
If the char. limit is reached, it allows only the delete and backspace keys to be pushed.
What it needs to work great, is a way to bind the "onselect" event in order to have the following behavior:
when the user selects the whole text with the mouse, and types a letter or a number, the whole text gets deleted and that letter appears.
This is something that most of us do when we want to replace some text with another, and I'd like my function to enable this.
Any ideas how?
If i may add something,
Your solution use keypress event, so the event is triggered before the new value of input is computed. That's why you have to check for special key like backspace , enter ... theses do not just add a character to the string so they require special treatment.
For this kind of processing, it's more convinient to have the handler triggered after the string computation. In that way, you can access the input value and modify it if it's not correct.
Unfortunately jquery does not support this event but you can use it with vanilla javascript method.
$(id)[0] // get the vanilla js element
.oninput = function(e){
this.value = this.value.substr( 0 , 10 ) // this.value contain the string after the key press processing
}

Jquery detect input focus

I am creating a conversion web app to teach myself Javascript. The user can input data with a number pad (basically a calculator without the operators). I also set up a function to detect keystrokes (1-9) which insert data just like the number pad. And also character 'c' which clears all data
My problem is that I also have a search field (which uses auto complete to enable the user to search for other conversions). I dont' want the user to search for something using the 'c' or number keys, and have it enter data into both the number pad, and search field.
My idea was to create a if statement to determine if the search field was active (focused), and if it was to change a variable (enabled) to false, thus disabling the keystroke detection.
The problem I am having is that the function holding the if statement with the focus attribute is not working.
If my rambling made no sense hopefully the code will clear things up.
Here is the if statement with the focus attribute
$(document).ready(function(){
if($(':focus').attr('#searchInput') == 'input')){
enabled === false;
}
});
Here is the code for key stroke detections (I omitted the redundant parts to save space
document.onkeydown = function(event){
var key = event.charCode || event.keyCode;
if(enabled === true){
if(key === 67){
clearInput(input); //Clears form input (input is my form ID)
}else if(key === 48){
writeInput(input, zero); //Zero is a var equaling 0
}
...
}else{
return false; //if enabled is false don't detect keystrokes
}
};
Any help would be greatly appreciated. If anything doesn't make sense I will be happy to explain (or edit the post.)
$(document).keyup(function(e){
if($('#searchInput').is(':focus')) {
return ; // search field is focused, ignore other part of function
}
var key = e.which;
// do your code here
});

Make enter key behave like tab key in Javascript

So far i have this being called on keypress.
function chkenter()
{
e = event.keyCode;
if (e == 13)
{
event.keyCode = 9;
return false;
}
}
but even though i set the keycode to 9 it doesn't tab over to the next control. How can i accomplish this? I'm working in Asp Classic.
What I ultimately want is for the focus to move to the next element. The next element's id, however, is not determined completely because its id was set in a loop, but at this point it exists. How can i set focus to the next control is the question.
It is an IE only script, so if you try to run it on firefox it wont work.
For it to work on IE, remove "return false;" from your code and dont forget to atach this function into "onkeydown" event.
You can do this using jQuery like so:
function checkKey(e){
if( e.keyCode == 13 ){ // if enter key
var e = jQuery.Event('keydown'); // create a manual event
e.which = e.charCode = 0;
e.keyCode = 9; // set the new event to "tab"
$(this.target).trigger(e); // trigger the new event (on the document)
return false; // cancels the original "enter" event from executing
}
}
// lets say you bind the event on the whole document...
$(document).on('keydown', checkKey);

Which keycode for escape key with jQuery

I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key?
$(document).keypress(function(e) {
if (e.which == 13) $('.save').click(); // enter (works as expected)
if (e.which == 27) $('.cancel').click(); // esc (does not work)
});
Try with the keyup event:
$(document).on('keyup', function(e) {
if (e.key == "Enter") $('.save').click();
if (e.key == "Escape") $('.cancel').click();
});
Rather than hardcode the keycode values in your function, consider using named constants to better convey your meaning:
var KEYCODE_ENTER = 13;
var KEYCODE_ESC = 27;
$(document).keyup(function(e) {
if (e.keyCode == KEYCODE_ENTER) $('.save').click();
if (e.keyCode == KEYCODE_ESC) $('.cancel').click();
});
Some browsers (like FireFox, unsure of others) define a global KeyEvent object that exposes these types of constants for you. This SO question shows a nice way of defining that object in other browsers as well.
(Answer extracted from my previous comment)
You need to use keyup rather than keypress. e.g.:
$(document).keyup(function(e) {
if (e.which == 13) $('.save').click(); // enter
if (e.which == 27) $('.cancel').click(); // esc
});
keypress doesn't seem to be handled consistently between browsers (try out the demo at http://api.jquery.com/keypress in IE vs Chrome vs Firefox. Sometimes keypress doesn't register, and the values for both 'which' and 'keyCode' vary) whereas keyup is consistent.
Since there was some discussion of e.which vs e.keyCode: Note that e.which is the jquery-normalized value and is the one recommended for use:
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
(from http://api.jquery.com/event.which/)
To find the keycode for any key, use this simple function:
document.onkeydown = function(evt) {
console.log(evt.keyCode);
}
27 is the code for the escape key. :)
Your best bet is
$(document).keyup(function(e) {
if (e.which === 13) $('.save').click(); // enter
if (e.which === 27) $('.cancel').click(); // esc
/* OPTIONAL: Only if you want other elements to ignore event */
e.preventDefault();
e.stopPropagation();
});
Summary
which is more preferable than keyCode because it is normalized
keyup is more preferable than keydown because keydown may occur multiple times if user keeps it pressed.
Do not use keypress unless you want to capture actual characters.
Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.
Related snippet from JQuery doc
While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the key code. This
code corresponds to a key on the keyboard, including codes for special
keys such as arrows. For catching actual text entry, .keypress() may
be a better choice.
Other item of interest: JavaScript Keypress Library
Try the jEscape plugin (download from google drive)
$(document).escape(function() {
alert('ESC button pressed');
});
or get keycode for cross browser
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) alert('ESC');
if (code === 13) alert('ENTER');
maybe you can use switch
var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
case 27:
alert('ESC');
break;
case 13:
alert('ENTER');
break;
}
Just posting an updated answer than e.keyCode is considered DEPRECATED on MDN.
Rather you should opt for e.key instead which supports clean names for everything. Here is the relevant copy pasta
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "ArrowDown":
// Do something for "down arrow" key press.
break;
case "ArrowUp":
// Do something for "up arrow" key press.
break;
case "ArrowLeft":
// Do something for "left arrow" key press.
break;
case "ArrowRight":
// Do something for "right arrow" key press.
break;
case "Enter":
// Do something for "enter" or "return" key press.
break;
case "Escape":
// Do something for "esc" key press.
break;
default:
return; // Quit when this doesn't handle the key event.
}
// Cancel the default action to avoid it being handled twice
event.preventDefault();
}, true);
Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.
$(document).ready(function(){
// Set focus
setTimeout('window.focus()',1000);
});
$(document).keypress(function(e) {
// Enable esc
if (e.keyCode == 27) {
parent.document.getElementById('iframediv').style.display='none';
parent.document.getElementById('iframe').src='/views/view.empty.black.html';
}
});
I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...
if (keyCode == 27)
{
history.back();
if (window.event)
{
// IE works fine anyways so this isn't really needed
e.cancelBubble = true;
e.returnValue = false;
}
else if (e.stopPropagation)
{
// In firefox, this is what keeps the escape key from canceling the history.back()
e.stopPropagation();
e.preventDefault();
}
return (false);
}
To explain where other answers haven't; the problem is your use of keypress.
Perhaps the event is just mis-named but keypress is defined to fire when when an actualcharacteris being inserted. I.e. text.
Whereas what you want is keydown/keyup, which fires whenever (before or after, respectively) the user depresses akey. I.e. those things on the keyboard.
The difference appears here because esc is a control character (literally 'non-printing character') and so doesn't write any text, thus not even firing keypress.
enter is weird, because even though you are using it as a control character (i.e. to control the UI), it is still inserting a new-line character, which will fire keypress.
Source: quirksmode
To get the hex code for all the characters: http://asciitable.com/
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('enter,esc', function(event,handler){
switch(handler.key){
case "enter":$('.save').click();break;
case "esc":$('.cancel').click();break;
}
});
hotkeys understands the following modifiers: ⇧,shiftoption⌥altctrlcontrolcommand, and ⌘.
The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.
I have always used keyup and e.which to catch escape key.
I know this question is asking about jquery, but for those people using jqueryui, there are constants for many of the keycodes:
$.ui.keyCode.ESCAPE
http://api.jqueryui.com/jQuery.ui.keyCode/
$(document).on('keydown', function(event) {
if (event.key == "Escape") {
alert('Esc key pressed.');
}
});

Categories

Resources