Detecting enter key pressed - javascript

Are there any ways available in jquery to detect whether Enter key has pressed?
I know that we can use keycodes/charset to identify the Enter key press, but I do not need to hard code an integer value in my js script as it will become a magical number. I need to know whether there are any other possible ways to detect Enter key press, which is something like e.shiftKey for detecting shift key press using event object.
Thanks.

So, you want to detect the Enter key being pressed without hardcoding a 13 for the keycode.
Now, I could suggest using 6.5*2 as the keycode, then, but that'd be silly.
The real answer is that there is no built-in constant for the Enter key, like the Shift key has.
The reason Shift has it, is because that key is often pressed in combination with other keys. You can't detect a Shift keyDown event when pressing Shift+A, for example, because the event for the modifier has passed already when you're handling the keyDown event for the A.
Frankly, your only real option would be to hardcode a application-wide constant that says something along the lines of:
window.keyCodes = {
Enter: 13,
SomeKey: 99
}
Then you can check against it like this:
if(e.keyCode === keyCodes.Enter)
Or, it may be possible to write a function that compares the character of the entered key with a string that contains only a return, but then you'd just be hardcoding a return, any way.

The keycode for the enter key is : 13
if(e.keyCode == 13)
//do something...

This is the immediate way that people detect this particular event, but there are other ways to identify the number 13.
var DOM_VK_RETURN = 13;
$(document).on('keydown', function(e) {
var code = e.keyCode || e.which;
if(code == DOM_VK_RETURN) {
console.log("Enter key pressed");
}
});
However, if you do not want to use an integer to detect the key, we could use hexadecimal.
http://jsfiddle.net/hk2eL/3/

Related

Weird CTRL key detection in Firefox

I have an input on one of my pages that has listeners on it that perform formatting on values entered into it.
The field only allows certain input(numerical as well as certain other characters), which is controlled with a keypress and a keyup listener. The keypress prevents illegal input, and the keyup performs formatting(and also checks input, in case the user pasted something into the field instead of typing).
It worked fine in Chrome and IE (back to IE8, I don't care about anything earlier), but in Firefox I was unable to use the tab key, arrow keys, backspace, and was unable to copy or paste using ctrl+c/v
After some investigation I found that the problem lies with this listener:
$(this).keypress(function(e)
{
consumeIllegalFloatKeyPress(e);
});
In IE and Chrome, keys like tab, arrows and backspace weren't even triggering the listener, and keypresses like v and c would not trigger it either, when used with the ctrl key. However, in FF it picks up all the keypresses, which resulted in
consumeIllegalFloatKeyPress(e);
getting called, and finding that the keypresses were illegal.
The fix was easy enough - I have an array of legal inputs that is used to check what should be allowed, so I just added the charCodes for v and c, and put in a key for the ctrlKey as well.
What I am confused about is why these are being handled differently in different browsers? I thought that, since it was all javascript, that it would handle the CTRL key the same across all browsers.
If anyone has any information on this, or knows of somewhere I can read up more on it, I'd be very interested and grateful!
Try the below solution. This works perfect for my issue
function captureKeyPress(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
var ctrlKeyPressed = e.ctrlKey;
var key = e.which;
switch(e.key){
case "c": //right arrow key
if (!ctrlKeyPressed) {
alert('C pressed');
}
break;
}
}
window.addEventListener("keypress", captureKeyPress);
Let's have a look at official documentation:
jQuery keypress listener
2 important things can be read here:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
And:
This method is a shortcut for .on( "keypress", handler ) in the first two variations, and .trigger( "keypress" ) in the third.
Let's have a look at what the Javascript documentation says about keypress:
javascript keypress event
After a few clicks we see a nice table on this page
The table shows which browsers accepts certain keys, like non-printable keys (arrow keys, control, page down, ...) and which don't.
The final answer to your question is: if there is no set standard for something (like the keypress event), then browsers will do whatever they feel like doing. For Google chrome this means it allows CTRL + V, where Mozilla Firefox filters it.
Please try this solution:
$(document).on("keypress", this, function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
/* Example */
if (keycode === 27) {
alert("Escape key");
}
});
...and you can enable or disable keys what you whant.
I will give you one my function for this:
FUNCTION:
$.fn.pKey = function (key, callback) {
var key=key;
return this.each(function () {
$(document).on("keypress", this, function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode === key) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").pKey(17,function (e) {
/* disable CTRL*/
e.preventDefault();
})

A javascript regex to allow only Latin characters and other helpful keys

For an HTML input value, is it possible to define with JavaScript a regular expression that accepts only Latin characters (any case) and all other keys like backspace, delete, arrow keys, and also .dot, #at?
Is it for event key evaluation, not afterwards, that's why I need the arrow and the other keys.
You can use something like:
JavaScript
document.getElementById('foo').onkeydown = function (e) {
if (e.keyCode < 65 || e.keyCode > 90) {
e.preventDefault();
return false;
}
};
HTML
<textarea id="foo"></textarea>
This will limit you to enter only small letters. It should be a little modified to work also with uppers.
JSfiddle.
Unless you give more details, I think regex will not help you.
I don't know details of the key event you need to use, but I wrote myself a object like a dictionary, worked well in one of my projects, but of course its not fail proof, and it's very hard to be 100%, because of many keyboard layout and languages out there, and the unstandadized event handling in javascript and browsers implementations. I suggest reading first this article it helped me a lot http://unixpapa.com/js/key.html
My workaround for en-US english keyboards.
var Keys = { "BACKSPACE":8, "TAB":9,"ENTER":13,"SHIFT":16,"CTRL":17,"ALT":18, "PAUSEBREAK":19, "CAPSLOCK":20,"ESC":27, "SPACE":32, "PAGEUP":33, "PAGEDOWN":34, "END":35, "HOME":36, "LEFT":37, "UP":38, "RIGHT":39, "DOWN":40, "PRNTSCRN":44, "INSERT":45, "DELETE":46, "0":48, "1":49, "2":50, "3":51, "4":52, "5":53, "6":54, "7":55, "8":56, "9":57, "A":65, "B":66, "C":67, "D":68, "E":69, "F":70, "G":71, "H":72, "I":73, "J":74, "K":75, "L":76, "M":77, "N":78, "O":79, "P":80, "Q":81, "R":82, "S":83, "T":84, "U":85, "V":86, "W":87, "X":88, "Y":89, "Z":90, "WINKEY":91, "WINKEYR":92, "APPLICATION":93, "NUM0":96, "NUM1":97, "NUM2":98, "NUM3":99, "NUM4":100, "NUM5":101, "NUM6":102, "NUM7":103, "NUM8":104, "NUM9":105, "MULTIPLY":106, "ADD":107, "SUBTRACT":109, "DECIMALPOINT":110, "DIVIDE":111, "F1":112, "F2":113, "F3":114, "f4":115, "F5":116, "F6":117, "F7":118, "F8":119, "F9":120, "F10":121, "F11":122, "F12":123, "NUMLOCK":144, "SCROLLLOCK":145, "SEMICOLON":186, "EQUAL":187, "COMMA":188, "DASH":189, "PERIOD":190, "SLASH":191, "GRAVE":192, "OPENBRAKET":219, "BACKSLASH":220, "CLOSEBRAKET":221, "SINGLEQUOTE":222, "MMNEXT":176, "MMPREVIOUS":177, "MMSTOP":178, "MMPLAY":179, "MMREWIND":227, "MMFORWARD":228, "MYCOMPUTER":182, "MYCALCULATOR":183, "HELP":225, "Invalid!":0
}
you can use like
if(event.keyCode == Keys['RIGHT']) //go right
if(event.keyCode == Keys['LEFT']) //go left
if(event.keyCode == Keys['ENTER']) //do something
if(event.keyCode == Keys['ESC'] || event.keyCode == Keys['BACKSPACE']) //exit
You mentioned arrows and other keys, if you're using keys to bind something like a game, avoid using modifiers like CTRL ALT WINKEY ALTGR APPLICATION OPTION COMMAND they are a mess, there are so many inconsistencies, like Command key pretending to be Application key, the right alt as another control, etc, also some keyboards doesn't have a second alt, or ctrl. So its a hell of exceptions.

Is it possible to have multiple simultaneous key inputs with ProcessingJS?

I'm working on an RTS style webapp in processingJS, meaning that there is a little minimap that represents a larger map, which the user can only see a small part of at any given moment. I just added the ability to use arrow keys to navigate the map, i.e.:
void keyPressed(){
if(key == CODED){
switch(keyCode){
case(UP): //go up
case(DOWN): //go down , etc
However, I'd like to be able to let a user move diagonally by pressing a combination of two arrow keys. Right now, it seems like this is impossible to do, seeing as how "keyCode" can only seem to hold one value at a time.
Does anybody know any workarounds to this issue?
Best,Sami
As #Xenethyl pointed to in his link in the comments, one way to get around this is by keeping tracks of when a key is pressed and then watching for when the key is released. It is safe to assume that a key is held down in the period of time in between those two events.
I would just do the following in javascript:
document.onkeydown = keydown;
function keydown(evt) {
if (!evt) evt = event;
if (evt.ctrlKey && evt.altKey && evt.keyCode==115) {
alert("CTRL+ALT+F4"); }
else if (evt.shiftKey && evt.keyCode == 9) {
alert("Shift+TAB"); }
}
I haven't tested this - but have you tried:
void keyPressed(){
if(key == 'a' && key == 'b'){
println("this just happened");
}
}
If this works you can find the ascii values for the arrow keys instead of using key CODED.

javascript (jquery) numeric input: keyCode for '3' and '#' are the same

I need to set up an <input type="text" /> so that it will accept only numeric chars, backspace, delete, enter, tabs and arrows.
There's a lot of exemple around there, i started with something similar to this:
function isNumericKeyCode (keyCode){
return ( (keyCode >= 48 && keyCode <= 57) //standard keyboard
||(keyCode >= 96 && keyCode <= 105)) //Numpad
}
$('#myTextBox').keydown(function(e){
var handled = true;
var keyCode = e.keyCode;
switch(keyCode){
//Enter and arrows
case 13:
case 37:
case 38:
case 39:
case 40:
doSomethingSpecialsWithThesesKeys();
break;
default:
handled = false;
break;
}
if ( !handled
&& keyCode !== 8 //backspace
&& keyCode !== 9 //tab
&& keyCode !== 46 //del
&& !isNumericKeyCode(keyCode)){
handled = true;
}
return handled;
});
All that worked perfectly until I hit the "#" key. In my french canadian keyboard, the "#" has his own key (no shift implied) that returns keyCode 51, the same as the number "3".
I think that in US keyboard, the "#" is obtained by pressing shift+3, that may be why they have the same keycode.
Now I realize that I have to handle the shift and alt keys too, but that's another story.
It works differently with the jquery keypress event, which offer the charCode property, but I did not used it at first because of what the documentation says :
as the keypress event isn't covered by any official specification, the
actual behavior encountered when using it may differ across browsers,
browser versions, and platforms.
Also, I would need a workaround in that case to handle tabs, arrows and other special keys since they don't provide a charCode.
So the question is :
is there a way to allow only some specifics chars using the keydown event? And that, in a way that will work independently of the keyboard layout?
As a side quest : Which browsers may be problematics with the keypress event? I mean, currently I don't really care if my website does not support IE6. I am targetting recent browsers.
Edit
As someone pointed out in the comments, this method does not allow user to "ctrl+v" a number in the input. In my particular case this is really not a requirement to be able to paste a number. But this popped something in my head, the user still can right-clic > copy some text in the input, and in that case that could be anything. The more I think of it, the more it seems to me that I will need the keydown event to handle tabs and arrows, and another event to handle the input itself.
Edit2
A lot of beautiful answers here, but the award goes to mrtsherman for the use of input and propertychange events. I will use a combination of this answer for the numeric validation, plus the keyCode event as before for the special use of arrows, tabs and enter keys.
How about something like this. This should cover cut/paste and also rmb content. We monitor the textbox for any change in content. Then we use a regex to filter out characters based on a whitelist. This won't handle non-character key, but I think that is okay.
The \d flag says that only digits should be accepted.
http://jsfiddle.net/UXeva/1
$('#myTextBox').bind('input propertychange', function() {
var text = $(this).val();
if (isNaN(text)) {
$(this).val(text.replace(/[^\d]/gi, ''));
}
});
We bind to two events here. input for FireFox and propertychange for other browsers.
If older browsers are'nt an issue, the number input type should cover this.
<input type="number" />
If not you could use the isNaN javascript function
$("#number1").on('keyup', function() {
var myval = $(this).val();
if (isNaN(myval)) {
alert('numbers only!');
}
});
Personally I would do some regex filtering with a check to see if the value has changed, that will allow any character that does not change the value, like tabs, enter and arrows. With a regex you could also add or remove any character, or you could use \d for digits only or as below, [0-9]. Up to you really what your exact needs are?
var P;
$("#number2").on('keyup', function() {
var V = $(this).val();
if (V != P) {
$(this).val(V.replace(/[^0-9]/g,''));
}
P=V;
});
They could also be combined to something like this:
$("#number3").on('keyup', function() {
var V = $(this).val();
if (isNaN(V)) {
$(this).val(V.replace(/[^0-9]/g,''));
}
});
Here's a FIDDLE to test them out!
Why not do something like this? It uses a combination of the keyup() event and isNaN(). It'll work whether the user types with the keyboard or pastes a number.
The way it works is, as soon as the text changes, it will check if the value is a number. If not, it will trim the input until it is a number. So, if you enter 25s or 25ss, you will be left with 25.
This will work with ctrl+v paste as well. It won't work with right-click paste and for that reason, I have disabled right-clicking only on the textbox.
Live Demo
The Jquery
$(document).ready(function(){
$('#number').keyup(function(){
var input = this.value;
while (isNaN(input))
{
input = input.substring(0,input.length-1);
$('#number').val(input);
}
});
$('#number').bind("contextmenu",function(e){
return false;
});
});
jQuery also provides a shiftkey boolean on the event object:
$('#myTextBox').keydown(function(e){
if(e.keyCode === 51 && !e.shiftKey){
// '3' key pressed while shift was **not** held down (not '#')
}
});
EDIT I reread your question and changed the code above for !shiftkey

How to capture a backspace on the onkeydown event

I have a function that is triggered by the onkeydown event of a textbox. How can I tell if the user has hit either the backspace key or the del key?
Try this:
document.addEventListener("keydown", KeyCheck); //or however you are calling your method
function KeyCheck(event)
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8:
alert("backspace");
break;
case 46:
alert("delete");
break;
default:
break;
}
}
event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
Nowadays, code to do this should look something like:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
// Call event.preventDefault() to stop the character before the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
// Call event.preventDefault() to stop the character after the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
});
although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.
Details worth knowing:
Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).
Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.
There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".
One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.
On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.
The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".
Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
In your function check for the keycode 8 (backspace) or 46 (delete)
Keycode information
Keycode list
not sure if it works outside of firefox:
callback (event){
if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
// do something
}
}
if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)

Categories