JavaScript - CTRL KeyCode of 17 does not work? - javascript

I'm making an application that needs to detect whether or not the CTRL key was pressed.
My code is as follows:
document.addEventListener('keydown', function(event) {
if (event.keyCode != 13 || event.keyCode != 38 || event.keyCode != 40 || event.keyCode != 17)
{
// execute this
}
(The CTRL key is the last keycode in that if statement.)
After searching the internet it says to use 17 as the keycode, but it is still EXECUTING "// Execute this" if i press CTRL.
It's not supposed to execute it.
All other keys work properly in the if statement, and I'm using Chrome 31 stable/official.
I am also using 'keydown' and not 'keypress' as you can see.
Thanks in advance for help!

This condition
event.keyCode != 13 || event.keyCode != 38 || event.keyCode != 40 || event.keyCode != 17
will always be true. This can be proven with two cases.
If event.keyCode is 13, then event.keyCode != 38 will cause the expression to return true because 13 != 38.
If event.keyCode is not 13, then the condition event.keyCode != 13 will cause the expression to return true.
I believe that you are wanting to use the && operator instead of the || operator.
Also, instead of checking event.keyCode !== 17, I think it is more readable to use !event.ctrlKey because it tells the reader of the code that you are checking about the ctrl key, whereas you have to look up 17 in a keycode table in order to find out what it means.
(As an aside, the !== and === operators are preferred in the Javascript community over the != and == operators.)

1 Change the or operator to an and operator (&&)
2 Fix your code errors, missing a semicolon and close parentheses
Your final code should look like this:
document.addEventListener('keydown', function (event) {
if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 17) {
alert(event.keyCode);
}
});
DEMO

Related

keycode for numerics only | javascript

I have this piece of code. According to keycodes here
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html
this code should work but for some reason I am getting these characters as true.
eiadfghcb.
function validate(event) {
var keycode = event.keyCode;
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
return false;
}
}
html:
<asp:TextBox ID="txtImp" runat="server" Height="23px" Width="80" onkeypress="return validate(event)" onkeyup="calc()"/>
The following code should work for you:
function validate(event) {
var code = event.code;
if (typeof code !== "undefined") {
var
codeBeginning = code.substr(0, code.length - 1);
if (code === "Period" || code === "NumpadDecimal" || code === "Backspace" || ((codeBeginning === "Digit" || codeBeginning === "Numpad") && !parseInt(code.substr(code.length - 1)).isNaN())) { // key pressed is one of the "."-keys, the "Backspace"-key or one of the number-keys.
return true;
}
return false;
}
var keyCode = event.which || event.keyCode;
if (keyCode === 8 || keyCode === 46 || (keyCode >= 48 && keyCode <= 57)) {
return true;
}
return false;
}
Explanation regarding to why your code didn't work.
The first condition in your if-statement !(keycode == 8 || keycode == 46) will indeed evaluate to true when the key pressed is neither the decimal point-key or the BACKSPACE-key.
However the second and third condition will conflict with one another. This can be show by the following example:
The user presses the Numpad 2-key which (in my case) results in 50. This value does comply to the second condition as 50 is both higher than 48 and lower than 57, but it will not comply to the third condition as 50 is lower than 96.
As both the second and third condition will have to result to true and there is always one of the two that will result in false the code will never do what you intend it to do.
Disclaimer
My previous answer stated that KeyBoardEvent.keyCode is unreliable and resulted in an inability to capture the right keys on my machine.
Even though I'm now unable to reproduce this issue I would still advice you to only use KeyBoardEvent.keyCode when absolutely necessary (as the documentation of KeyBoardEvent.keyCode does state that it is implementation specific), and use KeyBoardEvent.which whenever possible.
Explaination regarding to why my code works.
As the KeyBoardEvent.keyCode relies heavily on the browser implementation thereof, I've chosen to using it as much as possible by instead using KeyBoardEvent.which.
However as both of these properties have become deprecated I've also used KeyBoardEvent.code to make sure that the solution adheres the lastest KeyBoardEvent specification.
As such my solution uses KeyBoardEvent.code when available as it isn't deprecated or implementation specific. If KeyBoardEvent.code is unavailable it uses KeyBoardEvent.which as it is more consistent that KeyBoardEvent.keyCode. And finally if KeyBoardEvent.which (as is the case in older browsers e.g. Internet Explorer 8) it will have to use KeyBoardEvent.keyCode.
The issue:
Take a look at your third condition:
keycode < 96 || keycode > 105 //Where keycode is NOT between 96-105
Now look at the ASCII codes for the characters you entered:
a: 97
b: 98
c: 99
d: 100
e: 101
f: 102
g: 103
h: 104
It should now be obvious why your code is failing - You've included a condition that very specifically ignores the characters you're claiming "don't work".
keyCode vs charCode:
When it comes to keyCode, you're going to run into some cross-browser issues. For that reason you may want to consider checking both keyCode and/or charCode, as each works in a specific set of browsers. A simple way to be sure we're getting a value that's consistent is to do something like this:
var keycode = event.keyCode || event.charCode;
In the event that event.keyCode won't work, charCode will be used instead.
The solution:
If you simply want to ignore the condition that I pointed out as the problem, then just remove it:
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
return false;
}
That being said, your question doesn't say what your desire is... at all. It simply says that what you have "doesn't work for the characters mentioned".
Additional info:
As a side note, I'd be remiss if I didn't point out that your code is not exactly... friendly, for lack of a better word. An elegant way of resolving this is to replace condition lists with named functions, so the purpose and result is much more discernible, like so:
Bad:
if (sunny || not raining and warm || not(cloudy and raining) || not cold)
Good:
if (weatherIsNice(...))
Applied in your case it may be something like
function characterIsAllowed(keycode) {
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
return true;
} else {
return false;
}
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
if (characterIsAllowed(keycode)) {
return false;
}
}
Or, simplified one step further...
function characterIsAllowed(keycode) {
return (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105))
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
return !characterIsAllowed(keycode);
}

How to disable typing special characters only not up, down, left and right keys?

I need enable 0 to 9 also up, down, left, right, delete, tab, home, end and etc like (alt, ctrl)
Need Chrome and Firefox browsers
$('.commonNumber').keypress(function(event){
var nbr = event.charCode ? event.charCode : event.keyCode;
// Numbers 8 -> Backspace 9-> Tab
if ((nbr >= 48 && nbr <= 57) || nbr == 8 || nbr == 9 || nbr == 37 || nbr == 38 || nbr == 46 || nbr == 39 || nbr == 40){
return true;
} else {
return false;
}
I enable 37, 38, 39,40,46 this codes are left, up, right, down areo and delete button keys but this keys are also %&('. keys using the same code. so this keys are enabled
});
Your code for normalizing the character code is incorrect. See the bottom of this answer as to why.
If you are using JQuery, it normalizes the which property for you, so you should use event.which to examine the pressed key. The event.which property will be less than 32 for non-printable characters. Therefore, you should always ignore the key when event.which is less than 32. Otherwise, check if it is a character you want to accept.
I also think you should allow the rejected key events to bubble, so use event.preventDefault() to reject a key, rather than return false.
$('.commonNumber').keypress(function(event) {
var charCode = event.which;
if ((charCode >= 32) && ((charCode < 48) || (charCode > 57))) {
event.preventDefault();
}
});
jsfiddle
The code above will limit the accepted printable characters to just numeric digits, while still letting the arrow keys, the delete key, the backspace key, and other control keys to work. Key events will also bubble up, so when the Enter key is pressed, it will still submit the form (if the input element is part of a form).
If you are not using JQuery to handle the keypress event, you have to normalize the event properties yourself. According to this stackoverflow answer, you should do:
var charCode = (typeof event.which == 'number') ? event.which : event.keyCode;
Apparently all browsers, except IE<=8, support the event.which property. In IE<=8, the event.keyCode property holds the Unicode reference number for a printable key instead.
The issue with your original code is that in most browsers (other than IE<=8):
event.charCode is the Unicode reference number of the character for printable keys, and 0 for non-printable keys.
event.keyCode is a system and implementation dependent numerical code. (This is often 0 for printable keys.)
For instance, in Firefox you get:
Ampersand key: event.charCode = 38 and event.keyCode = 0.
Up arrow key: event.charCode = 0 and event.keyCode = 38.
Block or restrict special characters from input fields with jQuery.
You can either return false or call preventDefault() method on event variable.
//this script allows only number input.
$(document).ready(function(){
$("#age").keypress(function(e){
var keyCode = e.which;
/*
8 - (backspace)
32 - (space)
48-57 - (0-9)Numbers
*/
if ( (keyCode != 8 || keyCode ==32 ) && (keyCode < 48 || keyCode > 57)) {
return false;
}
});
});
//this script Not allowing special characters
$("#name").keypress(function(e){
var keyCode = e.which;
/*
48-57 - (0-9)Numbers
65-90 - (A-Z)
97-122 - (a-z)
8 - (backspace)
32 - (space)
*/ // Not allow special
if ( !( (keyCode >= 48 && keyCode <= 57)
||(keyCode >= 65 && keyCode <= 90)
|| (keyCode >= 97 && keyCode <= 122) )
&& keyCode != 8 && keyCode != 32) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type='text' id='name' placeholder='Enter your name'><br/><br/>
<input type='text' id='age' placeholder='Enter your age'>
</div>

Alternative for keyCode

I'm still at a novice level in JavaScript. I found one bug that's troubling me.
It's how keyCode doesn't seem to work on mobile devices (chrome). I just noticed that the mobile devices don't support keyCode.
I'm guessing I could do isNaN with an ! in stead of the code below but can't really figure out how to write it neatly.
var code = window.event.keyCode;
if ((code > 34 && code < 41) || (code > 47 && code < 58) || (code > 95 && code < 106) || code == 8 || code == 9 || code == 13 || code == 46){
window.event.returnValue = true;
return;
}
If anyone has a suggestion, it would be highly appreciated!
Feel free to comment on that microsite as well if you want to.
Sincerely,
Use jQuery and then use .which
.which standardizes keyCode and keyValue values between browsers
var code = event.which
if(code === 14){
//do something
}
Use jQuery's event.which
The event.which property normalizes event.keyCode and event.charCode.
It is recommended to watch event.which for keyboard key input.
$("<input-element-id-or-name>").keyup(function(e){
if(e.which === 14) {
// do something
}
});

i need to void dot(.) form user key press is not working

This is my jquery it is avoid all the symbols and alphabet but it allow a dot (.) i don't know why someone help me please. . .
$('.Number').keypress(function (event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 27 || keycode == 9 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
return false;
}
else {
return true;
}
});
You would have better to use a regex for that kind of check:
DEMO jsFiddle
$('.Number').keypress(function (event) {
if(!/\d/.test(String.fromCharCode(event.which))) return false;
});
According to: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes the correct keycode for . (period) is 190 (or 110), and you have not added this to your list.
Note that browser implementations (and thus results) may vary and I have no idea the effect of regional keyboard settings on these keycodes.
Because you haven't added the keycode for decimal point.
110 for . for full stop
190 for decimal point

JavaScript OR operator

Im having a hard time identifying what is wrong with my code
function NavCode() {
if ((event.keyCode > 31 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65)|| (event.keyCode > 90 && event.keyCode < 97)|| (event.keyCode > 122 && event.keyCode < 164)||(event.keyCode > 166) )
event.returnValue = false;
return false;
}
i aim on only allowing 0-9 numbers A-Za-z Letters ñÑ and special characters only
i am sucessfull on implementing 0-9-A-ZazñÑ
Using this code
function NavCode() {
if ((event.keyCode > 31 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65)|| (event.keyCode > 90 && event.keyCode < 97)|| (event.keyCode > 122 && event.keyCode < 164))
event.returnValue = false;
return false;
}
the problem with this is that it also alows ascii characters above 165 eg. ªº¿
But when i add ||(event.keyCode > 166) nothing on the special characters are working can you help me allow only
0-9-A-ZazñÑ?? im really having a hard time debugging the java script as im new to this
Thank you.
You are missing curly braces ({ and }) on the if, thus your return false; line is always executing, because an if without curly braces only conditionally executes the next single line.
Try this:
function NavCode() {
if ((event.keyCode > 31 && event.keyCode < 48) ||
(event.keyCode > 57 && event.keyCode < 65)||
(event.keyCode > 90 && event.keyCode < 97)||
(event.keyCode > 122 && event.keyCode < 164)) {
event.returnValue = false;
return false;
}
}
Now return false; will only execute if the if condition is true.
Assuming that event.keyCode is a unicode value you could do something like this:
if (String.fromCharCode(event.keyCode).match(/[^0-9A-Za-zñÑ]/)) {
event.returnValue = false;
return false;
}
It first converts the event.keyCode to a string (if you have access to the character, use that instead), then it uses a regexp to do a negated match (a ^ as a the first character in a range makes it a negated match)
It is a bit slower to use a regexp instead of checking the values of event.keyCode, but in my opinion it is more readable. Unless your code is running in a tight loop and processing megabytes of data per second, it should not be a problem.
You are missing, curly braces for the if condition and that is the main cause of the issue and if you are not applying curly braces then the statement right after the condition's closing parenthesis, only comes in the 'then' part of the if-then-else statement and all other statements are executed every time whether or not the condition in if is satisfied.

Categories

Resources