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.
Related
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")
}
}
Here is the code for keypress function, which is allowing only numbers
http://jsfiddle.net/lesson8/HkEuf/1/
But, for the same keycodes, keyup function is not working. I mean, if I use
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
The reason for using keyup is to get the current entered value in the textbox. If I use keyup function, I will get the current value. But, If I use keydown or keypress, I am getting the previous or existing value in the textbox
see the updated code with different functions
http://jsfiddle.net/dgireeshraju/HkEuf/7300/
this is the example with keydown, which is giving the existing value.
KeyUp fires after the character inserted only, as you can see your function is actually calling and warning message is displaying.
If you try the same code with KeyDown it will work as the event will be called before a character is inserted
//called when key is pressed in textbox
$("#quantity").keydown(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
Key up fires when the user releases a key, after the default action of that key >has been performed.
Keypress fires when an actual character is being inserted in, for >instance, a text input. It repeats while the user keeps the key depressed.
Your code is actaully working in both the cases (you can see the error message atleast ) but since this event are different so is the result. To make it work with keyup you need to empty the input element again since by that time the value has already been entered in input element
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$(this).val(''); //<--- this will empty the value in the input.
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
NOTE: However emptying the input does removes the complete value even when there are numbers in it so, I prefer keydown in such cases.
Updated
This is a little hack on input value but (I will still prefer to go with keydown), Use this if you really want keyup to work :). since I am modifying the default browser behaviuor, you might also need to think of lots of other cases here.
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
if(e.which != 13){ //<--- don't remove when entered is pressed.
$(this).val(e.currentTarget.value.substr(0, e.currentTarget.value.length - 1));
}
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
console.log(e.currentTarget.value);
});
working fiddle
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/.
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.
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.