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)
})
Related
I am trying to compare 2 characters (or key codes) to check if the letter on the screen is the same as the pressed character.
Sadly, all the keyDown results are in upper-case, and I would like to know if there's a different way that gets input as lower-case instead of manually changing all the input.
Here's my code:
document.onkeydown = function keyDown(e) {
if (!e) e = window.event;
if (e.keyCode == currentCharacter.charCodeAt(0)) {
// Input matches the current character.
} else {
// Input does not match the current character.
}
}
In this example, e.keyCode always returns the keycode for an upper-case version of the character I pressed.
According to this,
Using keyPress event rather than keyDown might be the answer.
How about converting the keyCode to a char, and the lowercase it..
document.onkeydown = function keyDown(e) {
if (!e) e = window.event;
var keyPressed = String.fromCharCode(e.keyCode).toLowerCase()
if (keyPressed == 'a') {
// Input matches the current character.
} else {
// Input does not match the current character.
}
}
I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.
I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:
function filterNonDigits(evt)
{
var event = evt || window.event;
var keyentered = event.keyCode || event.which;
keyentered = String.fromCharCode(keyentered);
//var regex1 = /[0-9]|\./;
var regex2 = /^[a-zA-Z.,;:|\\\/~!##$%^&*_-{}\[\]()`"'<>?\s]+$/;
if( regex2.test(keyentered) ) {
event.returnValue = false;
if(event.preventDefault) event.preventDefault();
}
When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.
So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.
New Update:
So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj))
{
$('#mobileno').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
}
else
{
$('#mobileno').on('keypress',function(e){
var deleteCode = 8; var backspaceCode = 46;
var key = e.which;
if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0)
{
character = String.fromCharCode(key);
if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' )
{
return true;
}
else { return false; }
}
else { return false; }
});
}
Thanks.
The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
// bind input
} else {
// bind onkeyup
}
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace
// you can add code for left,right arrow keys
{
$(this).removeClass('error');
return true;
}
else
{
$(this).addClass('error');
return false;
}
});
Fiddle: http://jsfiddle.net/PueS2/
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
var event = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
http://jsfiddle.net/mEvSV/1/
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
/\d/ is equivalent to the above described /[0-9]/. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
This is a bit more concise...
this.value = this.value.replace(/\D/gm, '');
im having a slight issue, with trying to programmatically find out the keycode value of a char. this is what I have at the moment.
var delimiter = ',';
//some where down the page
control.keyup(function(e)
{
var key = delimiter .charCodeAt(0);
if(e.keycode == key)
{
//do something
}
}
So when I press the ',' on the keyboard key has a value of 44 whilst e.keycode is 188. How to find out the keycode value of the variable delimiter ?
The keyup event returns a keycode not an ASCII code. If you switch to the keypress event you can retreive the ASCII code. This should match the value received by charCodeAt which returns the unicode value of a character, which happens to align with the ASCII code for the first 128 characters. See this reference.
var delimiter = ',';
var key = delimiter.charCodeAt(0);
document.getElementById("test").onkeypress = function(e){
if((e.keyCode || e.which) == key){
alert("Cat's out of the bag! OHHH YEAH!");
}
};
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.
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".