Converting keystrokes gathered by onkeydown into characters in JavaScript - javascript

I try to convert keystrokes into chracters.
In other question someone recommand to use the onkeydown function because onkeypress gets handeled differently by different characters.
I don't know how to handle special chracters like ยด ` ' ( ) that might be different in different keyboards around the world.

For keys that have printable character equivalents, you should use the keypress event because you can retrieve character codes from the keypress event, which is generally not possible for keyup and keydown events.
The event properties you need are which and keyCode - pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode but it seems all such browsers also have which, so charCode is never needed. A simple example:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
Here is a useful reference page.

document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
//a
var lx = document.getElementById('location');
typeIt("a");
}
else if (e.keyCode == '66') {
//b
var lx = document.getElementById('location');
typeIt("b");
}
else if (e.keyCode == '67') {
//c
var lx = document.getElementById('location');
typeIt("c");
}
}
This should successfully convert the key code you press into a string letter, which you can use in a bigger function. It takes more time, but I found it is highly compatible with most browsers and keyboards (whatever the language may be.) I used this code in a text editor project which would be distributed to friends in several countries, so I am certain it will work. Note: the function above only includes the letters "A", "B", and "C".

Related

jQuery composition event is undefined

I do not want users to enter numbers or special character within a name input field and I have achieved this with the following code:
jQuery(document).ready(function() {
jQuery(".txtOnly").keypress(function(e) {
var key = e.keyCode;
if(key < 97 || key > 122) {
e.preventDefault();
}
});
});
But I want to avoid numbers and special characters from microsoft IME Japanese Keyboard as well though the keypress does not work so I am using a jQuery composition event which is working but it always returns undefined, so I am unable to get the key code or the value this way.
My Code:
jQuery(document).ready(function() {
jQuery(".txtOnly").on('compositionupdate', function(e) {
var keyCode = e.keyCode;
alert(keyCode); //Undefined
console.log(e.data); //Undefined
});
});
How I can get the keycode using a composition event or what other solution can I use for the Microsoft IME Japanese Keyboard?

Allow arrow keys in Regular Expression

I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
#Html.TextBoxFor(model => model.ProductName, new { #class = "form-
control", #onkeypress = "return OnlyAlphaNumeric(this);", #onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
Your problem has nothing related to regular expressions.
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
Demo
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
Demo
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
You can try this, it may solve your problem.
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}

Add An Even listener For any letter keys pressed?

I am wondering how to create an event listener, so that when any of the character keys are pressed a form pops up and the first input is in focus and is receiving the input, sort of like the just type search style for the webOS 2.0 operating system, but for a contact form. Is there anyway to do so? In case your not familiar here is a link to the webos just type feature
http://www.youtube.com/watch?v=ixPsB7-tVGo
I don't know if you can only subscribe to letter keys.
Your best bet would be to use jQuery to subscribe to .keydown() / .keyup() and check the keycode of the event to see which letter it is. If it's not a letter, don't do anything.
Like this:
$('#target').keydown(function(event) {
if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
// play that funky music.
}
});
More on $.keydown.
List of key codes.
Use the keypress event for anything character related. keydown and keyup cannot be used reliably for this purpose. The following is adapted from my answer to a related recent question:
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
};

Detect printable keys

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.
Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?
Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">
Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.
This method is much more reliable simply because unlike event.which, event.key is already standardized.
I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.
I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});
If you need to identify printable key just for change detection as user change the input, you could use oninput event.
let isPrintableKey = event.key.length === 1 || event.key === 'Unidentified';
If you do not include: || event.key === 'Unidentified' your code will not work on mobile browsers.

How to get the key pressed and put into array in JavaScript?

How do I get the key that was pressed and, instead of returning the key code, put that key into an array?
For example, the user will press 'a'. Then, the code will put 'a' - not the keycode for the character - into an array.
Thanks in advance!
What about something like this?
var your_array = [];
document.onkeydown = function (e) {
var keyPress;
if (typeof event !== 'undefined') {
keyPress = event.keyCode;
}
else if (e) {
keyPress = e.which;
}
your_array.push(String.fromCharCode(keyPress));
return false; // Prevents the default action
};
UPDATE: If you require accurate character information (such as, the distinction of uppercase from lowercase, and other things), make sure to check out #Tim Down's comments below and his other answer.
You need the keypress event for this. keydown and keyup cannot be used reliably to get character information. An excellent and detailed explanation of JavaScript key events is at http://unixpapa.com/js/key.html
var charsTyped = [];
document.onkeypress = function(evt) {
evt = evt || window.event;
// Ensure we only handle printable keys
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (charCode) {
charsTyped.push(String.fromCharCode(charCode));
}
};
Daniel's answer is perfect, but if you want to get the actual character (not the numerical code), you can use this function:
String.fromCharCode(code);
See MDN for more info.
In your event handler (assuming e is the event object):
myarray.push(String.fromCharCode(e.charCode));
Notice how fromCharCode returns the character given a Unicode character code. Also notice how I used charCode instead of keyCode as it's more correct in returning the character code, which sometimes is different to the keycode (you want the character).
I wrote a library called keysight to translate keyboard events into keys and characters.
var yourKeyArray = []
node.addEventListener("keydown", function(event) {
var key = keysight(event).key // ignores shift keys, so 'A' is given as 'a'
// var char = keysight(event).char // only characters, and differentiates between 'A' and 'a'
yourKeyArray.push(key)
})

Categories

Resources