how to capture backspace key code in android browser - javascript? - javascript

I have a page made in pure HTML Javascript... I handle the keyup code and I need to get the key code, when key code == 8 (backspace) special task must be run... but if I open the page in android browser, chrome, or whatever... backspace doesn't return any key code...
I've made:
$( '.input-cell' ).bind( 'keyup', function( e ){
var keycode = e.keyCode ? e.keyCode : e.which;
alert( keycode );
if( keycode == 8 ) {
.....
}
});
The alert returns me all the keycodes but the backspace... is there any way to capture the backspace press event?

input change event
$('#myinput').bind('input', function(){
// code
});
backspace
$('#myinput').on('keypress', function() {
//code
}).on('keydown', function(e) {
if (e.keyCode==8) {
//code
}
});

Another solution can be check for the length of the characters before, and after, if it has less than one character than before, then clearly it was a backspace that fired, in my case I was using only one input with one character and needed to go back to the previous input after hitting a backspace, for my case I only got also 0 and 229 within the android keyboard, so I did this:
$('input').on('keydown', function (e) {
switch(e.keyCode){
case 229:
case 0:
if($(this).val() == '')
$(this).prev().focus();
break;
}
});
The same can be achieved by checking the characters, of course this will only be in the case of a backspace in the android keyboard device, is just a workaround, hope it helps.

Related

Altering the keypress event of certain keys in 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.

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.

jQuery not detecting modifiers on keyup

When I run the following code and press the command key on my Mac (using Chrome), metaKey is set for keydown but not for keyup. Am I doing something wrong? I'm just trying to track the meta key being pressed so I can use it inside my JavaScript - if there's a better way please let me know :-)
var metaPressed = false;
$(document).keydown(function(e) {
console.log('keydown ' + e.keyCode);
if (e.metaKey || e.ctrlKey) {
console.log('meta pressed');
metaPressed = true;
}
});
$(document).keyup(function(e) {
console.log('keyup ' + e.keyCode);
if (e.metaKey || e.ctrlKey) {
console.log('meta unpressed');
metaPressed = false;
}
});
Here's the console output for the relevant keys
// Pressing cmd
keydown 91
meta pressed
keyup 91
// Pressing control
keydown 17
meta pressed
keyup 17
// Pressing non-meta like spacebar
keydown 32
keyup 32
I get it now, I was misunderstanding how jQuery handles modifier keys. Thanks to #adeneo for the prompt that got me thinking correctly.
Also, if you press keys while holding a meta character, e.g. press M-x, jQuery doesn't send the keyup for 'x' until it the 'M' is also released. So you don't have to worry about things like "meta down, x down, x up, meta up" happening
You won't be able to retrieve that information from the keyup. I would recommend to use this (e.keyCode === 17 || e.keyCode === 91) as test case (which are CTRL and META respectively)
I'm using React and noticing the same issue. e.metaKey works on keydown but not keyup. e.keyCode is 93 for both, however.

how to accept only alphabetical pressed keys ( for "autocomplete" purpose )

am wondering ... how to only accept alphabetical pressed keys from the keyboard .. i am using the jQuery .keypress method ... now i wanna know how to filter the passed key ...
i am trying to build a simple autocomplete plugin for jQuery ...i know a about jQuery UI, but i want to do it myself ...
thanks in advance :)
You can bind a function to the field that replaces anything that's not in the a-z range.
<input name="lorem" class="alphaonly" />
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
$(this).val( $(this).val().replace(/[^a-z]/g,'') );
});
</script>
Source: Allow text box only for letters using jQuery?
In your callback, you can check the event's keyCode property. If you want to disallow the key being entered, simply return false. For example:
$('#element').keypress(function(e)
{
if(e.which < 65 || e.which > 90) //65=a, 90=z
return false;
});
Note that this won't really work very well. The user could still paste in other text, or use a mouse-based entry device, or any number of other things.
I've edited this based on Tim Down's comment and replaced keyCode with which, which is correct across keydown, keyup, and keypress events.
The following will prevent any character typed outside of a-z and A-Z from registering.
$("#your_input_id").keypress(function(e) {
if (!/[a-z]/i.test(String.fromCharCode(e.which))) {
return false;
}
});
This won't prevent pasted or dragged text appearing. The surest way to do that is the change event, which is only fired once the input has lost the focus:
$("#your_input_id").change(function(e) {
this.value = this.value.replace(/[^a-z]+/gi, "");
});
This worked for me, it only accepts letters no special characters or numbers
$("#your-input-here").keypress(function (e) { return validateAlphaKeyPress(e); });
function validateAlphaKeyPress(e) {
if (e.keyCode >= 97 && e.keyCode <= 122) {
return true;
}
return false;
}

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