e.which only working with capital letters - javascript

I've been messing with JQuery codes that will only run on key presses, and they are not working unless I type a capital letter. Has anyone else had this issue?
Ex:
$(document).keypress(function(e) {
if (e.which == 70) {
console.log("test");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Only works if i type "F," but not "f"

Try listening to the keydown event instead of the keypress event, and it works as expected:
$(document).keydown(function(e) {
if (e.which == 70) {
console.log("test");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works because:
Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events.
So, to check that the "f" key has been depressed, use keydown to check the key that was depressed (the .which property will hold the keyCode of the capital letter of the pressed key, no matter whether shift is down or not), while "keypress" will have the keyCode of the character that would get typed, which would be "F" if shift is down (keycode of 70, which is not the same as the keycode for "f", which is 102)
$(document).keypress(function(e) {
console.log(e.which);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The keyDown usage suggested by CertainPerformance is absolutely correct. But I just wish to add-on a detail about e.which in jQuery.
The e.which event property is different in jQuery than in vanilla JS... Where it is "normalized".
It actually is deprecated for vanilla JS, but absolutely not for jQuery.
From jQuery's documentation:
Most properties from the original event are copied over and normalized to the new event object.
Now if you want to make the difference between f and F, you have to use the e.shiftKey property in your logic.
$(document).keydown(function(e) {
if (e.which == 70 && !e.shiftKey) {
console.log("Lowercase f");
}
if (e.which == 70 && e.shiftKey) {
console.log("Uppercase F");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And yes... That is really confusing.

Related

Detect Ctrl + A in keyup event

I want to detect the Control + A event in input. I can find the Control + A event, but the function is continuing even after return false.
jsFiddle - http://jsfiddle.net/f6rcgpmh/4/
$('.searchTerm').keyup(function(e) {
$("#status").text("");
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
console.log("Control pressed");
e.preventDefault();
return false;
}
}
$("#status").text("This should not work if Ctrl + A is pressed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="search" class="search">
<input class="searchTerm" placeholder="Filter Books...">
<input class="searchButton" type="submit">
</form>
<div id="status"></div>
I want this to work in keyup not in keydown. Because I am using autosearch and I don't want to call function before keyrelease. And also Ctrl + A won't highlight text in keydown when it returned false.
Actually the function stops. What you are experiencing is that two keyup events trigger: the one from ctrl and the one from A.
The first one returns as expected because it does fill the requirements: ctrlKey == true and keyCode == 65 || keyCode == 97.
But the second one, there will be only one key pressed so both statements can't be true together:
If you last released the ctrl, then ctrlKey is true but keyCode == 65 || keyCode == 97 is not.
If you last released the A, then ctrlKey is now false.
Then the line which sets #status to an error message is run.
Actually it's not. You must change your event from 'keyup' to 'keydown'. Then try it again. You can check this fiddle. http://jsfiddle.net/ebilgin/f6rcgpmh/5/
If you need control on autocomplete, you have to put your controls before sending the data.
The Ctrl keyup event trigger causes your problem. I added another condition to your code,
if (e.keyCode == 17) // Ctrl key, fires at Ctrl's keyup.
return false;
You can check my new fiddle, http://jsfiddle.net/ebilgin/f6rcgpmh/10/.

Keyboard sequence to click on button

I would like a system administrator to easily create new accounts in an application. I was thinking keys alt and shift would trigger the "Create New User" button or defaultButton2 in my application. I can get one key to work, but combining both keys doesn't seem to work.
$(document).ready(function () {
$("input").bind("keydown", function (event) {
var keycode = (event.keyCode ? event.keyCode :
(event.which ? event.which : event.charCode));
if (keycode == 16 && keycode == 18) {
document.getElementById('defaultButton2').click();
return false;
} else {
return true;
}
});
});
The keydown event (mdn) has booleans for the shiftkey, altkey and control key to detect when combinations of buttons are pressed. You can therefore just check those. The keyCode is only for the last key pressed.
If you want to detect other keys, e.g. if "a" and "s" are pressed at the same time, you need to mess around with custom keydown and keyup events and track things yourself.
$('body').on( 'keydown', function(e) {
if( e.altKey && e.shiftKey ) {
console.log( "Both pressed!" );
}
} );
body {
background-color: #DDDDDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click Here
You almost did it right...
$(document).ready(function(){
$("input").keydown(function(e) {
// 18 is the key for alt
if(e.keyCode == 18 && e.shiftKey) {
$("button").click();
}
});
});
Here is a working JSFiddle and if you're looking for the JS keycodes have a look here.

Alert when any key is pressed

I am using the below javascript to alert when the user presses delete, backspace and space inside a textbox. I need to alert if any key is pressed inside the textbox and probably I can mention the keycode in the script for each key. But can anyone tell me if there is any other way to alert when any key is pressed?
function doCheck() {
var keyCode = (event.which) ? event.which : event.keyCode;
if ((keyCode == 8) || (keyCode == 46) || (keyCode == 32))
alert('The column is readonly and is non-editable');
event.returnValue = false;
}
Can you try this, Event Handlers onkeypress
onkeypress="KeyPressCheck(event)"
Javascript:
function KeyPressCheck(event){
console.log('pressed::'+ event.keyCode);
}
Ref: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onkeypress
Use jQuery to attach the event, otherwise you will have to add on handler attributes to every element manually. Try this:
$('.texboxes').keypress(function(e) {
if ((e.which == 8) || (e.which == 46) || (e.which == 32)) {
alert('The column is readonly and is non-editable');
event.returnValue = false;
}
});
function doCheck(event)
and pass event where you are using this function
for eg.
onclick="doCheck(event)"
You can use JQuery Keyup Event handler to find which key is press.
$( "#SelectorId" ).keyup(function( event ) {
//check for which key is pressed.
if ((event.which== 8) || (event.which== 46) || (event.which== 32)){
alert("Some message");
event.preventDefault();
}
});
Why to use keyup event :
keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

Trying to get numbers from keypress document, javascript

it seems simple, but I couldn't figure how to intercept numbers on javascript from Document DOM
$(document).keypress(function (e) {
if (e.keyCode == xx) {
alert();
}
});
Numbers are 48 through 57, so...
$(document).keypress(function (e) {
var key = e.keyCode || e.charCode;
if (key >= 48 && key <= 57) {
alert('You pressed ' + (key - 48));
}
});
See demo
Source: http://www.quirksmode.org/js/keys.html
Keypress events yield a keyCode of 0 in Firefox, and the ASCII character value everywhere else. Keypress events yield a charCode of the ASCII character value in Firefox. Therefore, you should use (e.keyCode || e.charCode) to get the character value.
Also note that your code also wouldn't work because alert should accept one argument. In Firefox, at least, calling alert with no arguments throws an exception.
With those two issues fixed, your code will now be:
$(document).keypress(function (e) {
if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
alert('something');
}
});
Example: http://jsfiddle.net/gRrk6/
$(document).keydown(function(event){
if(event.keyCode == 13) {
alert('you pressed enter');}
});
replace 13 with the keys code, see here for details:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
you should notice the differences between events [ keyCode, charCode, which ]
and this test page affected by the browser i.e i tested it on safari
the onKeyPress always empty
JavaScript Event KeyCode Test Page

Combination of Keypresses using JS / jQuery ( Escape & Shift +Escape )

Is there a way in js/jQuery how to have these two combinations of keypresses?
ESCape key
and
SHIFT + ESCape key
when I implemented it using:
document.onkeydown = function(e){if (e == null) {keycode = event.keyCode;}
else {keycode = e.which;}
if(keycode == 27){closeAll();}}
//upon pressing shift + esc
$(document).bind('keypress',function(event)
{
if(event.which === 27 && event.shiftKey)
{
closetogether();
}
});
The escape button works perfectly but the one with the shift + esc is getting confused I think because it's doing nothing. Don't worry the function works as when I change the combining key 27 to 90 (z) for example it works just fine.
Can someone opt me for a better way ?
Why don't you bind the keydown event using jQuery? That way you would already have a normalized event variable. You can also check the status of the shift key in the same handler.
These events send different keycodes back. Use keyup/keydown for capturing certain keys by scancodes and use keypress to capture actual text input by characters.
$(document).bind('keydown', function(event) {
if(event.which === 27){
if(event.shiftKey){
closetogether();
} else {
closeAll();
}
}
});

Categories