Detect Ctrl + A in keyup event - javascript

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/.

Related

e.which only working with capital letters

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.

Is Keycode for Delete and Dot same using JQuery/Javascript?

I am trying to catch keycode for Dot and Delete but on different events.
function validateSomething(eve) {
var charCode = (eve.which) ? eve.which : eve.keyCode
if (charCode == 46)
console.log("Killer Brand")
}
When i press DOT or Delete in textbox; on keypress call above function; the if statement executes on both. Why? How to resolve then?
Use keydown event instead. As W3schools says:
The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT,
ESC) in all browsers. To detect only whether the user has pressed a
key, use the onkeydown event instead, because it works for all keys
So it can be detected with same codes on keypress. Read more here:
So, here is a working example: http://www.w3schools.com/jsref/event_onkeypress.asp
<input type="text" onkeydown="validateSomething(event)" />
function validateSomething(eve) {
var charCode = (eve.which) ? eve.which : eve.keyCode
if (charCode == 46) {
console.log("Killer Brand")
}
}

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.

JavaScript can't capture "SHIFT+TAB" combination

For whatever reason I can't capture "SHIFT+TAB" combination.
I am using the latest jQuery.
Same result if I use other ajax/javascript, etc.
Here is a simple example that should work as I currently understand it...
event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...
function ShiftTab()
{
debugger;
if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
// if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
{
return true;
}
else
{
return false;
}
}
this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.
If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:
$(document).keyup(function (e) {
if (e.which === 9 && e.shiftKey) {
ShiftTab();
}
});
If you're into terse JavaScript:
$(document).keyup(function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
jQuery 1.7+ on syntax:
$(document).on('keyup', function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press
function ShiftTab(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode; // for trans-browser compatibility
if (charCode === 9) {
if (e.shiftKey) {
$('#controlName').focus();
return false;
} else {
return true;
}
}
I took this approach to deal with two specific problems:
onkeypress would not capture tab key press
When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
use same code inside keypress event.
the tab changes the element between keypress and keyup.
here we get event.key = tab and event.shiftKey = true.

Categories