Changing keyDown presses to lower case - javascript

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.
}
}

Related

Keycodes for meta keys[backspace][ctrl][alt] with upper and lower case letters

How to get keycode on keypress?
I know that keydown and keyup will give keycodes for all keys but without considering the case for alphabets
and also keypress will give case sensitive keycodes but donot give keycodes for meta keys like backspace, alt, ctrl, enter and shift. is there any method to get all the keycodes including meta and case sensitive keycodes? in javascript
I found a work around for this problem.
Events execute in this order
1, Key down
2, key press
3, key up
Steps to solve problem
1, use two events, key down and key press
2, cancel event in keydown if keycode is in range of capital letters
3, execute event in key up
var cancelKeypress = false;
$("body").keydown(function(event){
event = event || window.event;
var eliminateKeys = [];
for (var i = 65; i <= 90; i++) { //Capital Letters [A-Z]
eliminateKeys.push(i);
}
eliminateKeys.push(32); // space
cancelKeypress = eliminateKeys.indexOf(event.keyCode) == -1 ? false : true;
if (cancelKeypress) {
//return false;
}
else{
Main.processTrigger(event);// your processtrigger function
}
});
$("body").keypress(function(event){
if (cancelKeypress) {
Main.processTrigger(event); // your processtrigger function
console.log(event);
}
else{
//return false;
}
});

Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

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, '');

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

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

Converting keystrokes gathered by onkeydown into characters in 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".

Categories

Resources