Alternative for keyCode - javascript

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
}
});

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);
}

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 - CTRL KeyCode of 17 does not work?

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

Validation is not working in Mozilla but working in Google Chrome

I am facing problem in validation. It is working in google chrome, but not in Mozilla.
Like: I have a form where Name: ____ .
I want to put a validation so that the user can't write a numeric value.
Inside the javascript:
function checkerFunction1(e)
{
var charCode1=e.which || e.keyCode;
if((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
return true;
return false;
}
Inside the jsp page:
<input type="text" value="Name" onkeypress="return checkerFunction1(window.event)"/>
Why it is not working in Mozilla?
This should fix it:
function checkerFunction1(e)
{
e = e || window.event;
var charCode1=e.which || e.keyCode;
return ((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
}
The condition in the if's brackets is a boolean already. The if is not needed when you want to return a true or false, you were basically saying:
if(true)
return true;
else
return false;
Firefox was telling me "e is undefined"
You'll need to use the event object for that browser (as seen above)
preventDefault() is not needed. Returning false will prevent Firefox from entering a false key into the field.
You have forgotten to call e.preventDefault().
function checkerFunction1(e) {
e = e || window.event;
var charCode1=e.which || e.keyCode;
if(
(charCode1 >= 65 && charCode1 <= 90)
|| (charCode1 >= 97 && charCode1 <= 122)
|| (charCode1==32 || charCode1==8 || charCode1==46)
) return true;
return e.preventDefault(), false;
}
see this fiddle.
It is better practice to attach event listeners to DOM elements on window load rather than via html attributes as it separates your HTML from your JavaScript. It also has the added benefit of choosing when you want to capture the event itself.
You can still grab window.event inside the function if absolutely required for compatibility.
The "undefined problem" in Firefox comes from event being treated more like a keyword than a variable, so window.event === undefined but event !== undefined, therefore if you want to keep the thing as an attribute, you could do it like this
onkeypress="return checkerFunction1(window.event||event)"

Javascript keycodes not working in firefox but works well in chrome

I'm just doing my form validation wherein which Phone number has to be only numbers! The code works well in chrome but not in firefox and IE. pls give me some solution
My code is as follows
function noLet(event) {
if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode < 58) {
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
HTML:
onkeypress="noLet(e)"><label id="mobph"></label><font
size="1"><br>Max 10 numbers only allowed!</font>
May i suggest the following code to solve your problem. This is what i am doing. Tested and works like a charm in ie, chrome and firefox:
//return numbers and backspace(charCode == 8) only
function noLet(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >= 48 && charCode <= 57 || charCode == 8)
return true;
return false;
You can use the key/char code to detect whether the key pressed is a number or not a number. First you have to detect what the key/char code is cross browser (remember to use event.keypress as your event to further assure compatibility). Afterwards, you convert it from its decimal value to its character. Then you can parse it as an integer using parseInt() which will return NaN if the first value inside the function cannot be parsed as an int. And then prevent the default action if it is NaN.
var numbersOnly = function(e){
var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
chr = String.fromCharCode(charCode);
if(isNaN(parseInt(chr, 10))) e.preventDefault();
}
<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">
Because on Firefox, at least, it's charCode, not keyCode in the keypress handler, and "returnValue" is ignored (invoke preventDefault() to stop the insertion).
There's compatibility issue of browsers. Here is a solution which I found out in some RND. Hope so it'll help you somehow; Click Here

Categories

Resources