Get key value of a key pressed - javascript

I don't find how to get the value of a key pressed.
I currently have
$('#info_price').bind('keydown',function(evt){
alert(evt.keyCode);
but it return '49' when I press on 1 instead of returning '1'.
Edit: I'm aware that Ascii code of key '1'.
The final goal is to allow people to only write digit into the input. So i want to detect the non digit and not display them.

As it's told in comment it's ASCII code. To get it as character you can do:
alert(String.fromCharCode(evt.keyCode));

For those who google it now, like I am
$('input').on('keydown', function(e) {
console.log(e.key);
});​

Here is a fully done code for you to work with (not mine, but I used it):
http://www.selfcontained.us/2009/09/16/getting-keycode-values-in-javascript/
keycode = {
getKeyCode : function(e) {
var keycode = null;
if(window.event) {
keycode = window.event.keyCode;
}else if(e) {
keycode = e.which;
}
return keycode;
},
getKeyCodeValue : function(keyCode, shiftKey) {
shiftKey = shiftKey || false;
var value = null;
if(shiftKey === true) {
value = this.modifiedByShift[keyCode];
}else {
value = this.keyCodeMap[keyCode];
}
return value;
},
getValueByEvent : function(e) {
return this.getKeyCodeValue(this.getKeyCode(e), e.shiftKey);
},
keyCodeMap : {
8:"backspace", 9:"tab", 13:"return", 16:"shift", 17:"ctrl", 18:"alt", 19:"pausebreak", 20:"capslock", 27:"escape", 32:" ", 33:"pageup",
34:"pagedown", 35:"end", 36:"home", 37:"left", 38:"up", 39:"right", 40:"down", 43:"+", 44:"printscreen", 45:"insert", 46:"delete",
48:"0", 49:"1", 50:"2", 51:"3", 52:"4", 53:"5", 54:"6", 55:"7", 56:"8", 57:"9", 59:";",
61:"=", 65:"a", 66:"b", 67:"c", 68:"d", 69:"e", 70:"f", 71:"g", 72:"h", 73:"i", 74:"j", 75:"k", 76:"l",
77:"m", 78:"n", 79:"o", 80:"p", 81:"q", 82:"r", 83:"s", 84:"t", 85:"u", 86:"v", 87:"w", 88:"x", 89:"y", 90:"z",
96:"0", 97:"1", 98:"2", 99:"3", 100:"4", 101:"5", 102:"6", 103:"7", 104:"8", 105:"9",
106: "*", 107:"+", 109:"-", 110:".", 111: "/",
112:"f1", 113:"f2", 114:"f3", 115:"f4", 116:"f5", 117:"f6", 118:"f7", 119:"f8", 120:"f9", 121:"f10", 122:"f11", 123:"f12",
144:"numlock", 145:"scrolllock", 186:";", 187:"=", 188:",", 189:"-", 190:".", 191:"/", 192:"`", 219:"[", 220:"\\", 221:"]", 222:"'"
},
modifiedByShift : {
192:"~", 48:")", 49:"!", 50:"#", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 109:"_", 61:"+",
219:"{", 221:"}", 220:"|", 59:":", 222:"\"", 188:"<", 189:">", 191:"?",
96:"insert", 97:"end", 98:"down", 99:"pagedown", 100:"left", 102:"right", 103:"home", 104:"up", 105:"pageup"
}
};

In javascript each key has associated with a ASCII code
as follows
1-49
2-50
like this
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
So you need to map this values according to the keypress event.

The key code does not directly map to the character value. Instead, you need to look at the keypress event, which provides you with a charCode property. You can then use String.fromCharCode to turn that into a string.

You can detect all key values like this:
Here is working jsFiddle example.
$('textarea').keydown(function(e) {
var order = e.which;
console.log(order);
});​
Source.

To get the character of the ASCII:
String.fromCharCode();
to turn ASCII into a string.

Chrome and Opera today have Read only property data in event object.
It is written on MDN that currently this feature is "Working Draft".
https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data

Related

Jquery: An alternate method for fromcharcode() to convert integer to character

I'm coding a chat box. And the Characters that I enter, is not reflected as it is.
This is basically the code I'm using.
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
});
And so when I type (lower-case) "a", console tab shows me "A".
special characters will not get reflected unless I create separate condition for it.
Could someone help me with a different function which does it all by itself, and returns a string as entered by the user. Or a different approach to this challenge all together. Thanks.
Actual code - chat.js
var str='';
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(c));
}
});
});
So basically the every character entered would get concated to the string. and Enter key would dump the text to console.
It's seems that trying to get the value of event.which in keydown event could lead you to a wrong ascii code (What you need to pass to String.fromCharCode).
See https://stackoverflow.com/a/10192144/3879872
I don't know if it fits your needs, but you could try:
$(document).ready(function(){
$(".entry").keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
});
(Note the use of keypress instead of keydown)
EDIT: Added working Demo
var str = '';
$(document).ready(function() {
$(".entry").keypress(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(event.which));
}
console.log('Formated Text', str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="entry"></textarea>

How do I get key values in HTML/Javascript

Okay, so i understand how to get the key value while using an input field... but I am taking about key values that are pressed while your browser isn't focused in any text box or text area.
I am trying to make a onscreen keypad that has buttons for 0, 1, 2, .. 9... however I want the user to be able to press the buttons with the keys on the keyboard.
I've seen this done in some websites, where if you press the S key on the homepage, it will take you to the signin screen. Facebook also does the L key, to like a photo.
So the question is: How do I get the key values in javascript, when the cursor isn't focused.
If you are using JQuery you just add the event handler to the document...
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.which);
});
(From http://forum.jquery.com/topic/how-to-catch-keypress-on-body)
Edit for zzzzBov's comment...
From the JQuery KeyPress documentation:
To determine which character was entered, examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.
you need to use window.onkeydown and then check for the keys you're interested in.
https://developer.mozilla.org/en-US/docs/Web/API/window.onkeydown
You should listen on key press event.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
alert("Character typed: " + String.fromCharCode(charCode));
};
For more info Look here Link
You need to add an event listener to the window. Then in the event handler, you get the keyCode property from the passed-in event. KeyCodes are semi-arbitrary in that they don't directly map to what you might think, so you have to use a table (first result on google: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) to identify the keycodes you care about.
window.addEventListener('keypress',function (evt) {
switch (evt.keyCode) {
case 48:
zeroKeyPressed(); break;
case 49:
oneKeyPressed(); break;
...
}
}, false);
You would use a key press event.
Here's an example for your usage:
window.addEventListener('keypress', function (event) {
var key_code, key;
event = event || window.event; // IE
key_code = event.charCode || event.keyCode || event.which || 0;
key = String.fromCharCode(key_code);
// prevent keys 0-9 from doing what they normally would do
if (key_code >= 48 && <= 57) {
event.preventDefault();
alert('The user pressed ' + key);
}
}, false);
Using plain js, you can use this in your layout.htmlcs, at the beginning:
#{
<script>
sessionStorage.setItem("ProductionHostURL", '#System.Configuration.ConfigurationManager.AppSettings["ProductionHostURL"]');
</script>
}
<!DOCTYPE html>
Then in your main js file of the layout.htmlcs, you can use this a method liked this:
var urlBaseProduction;
var urlBaseDevelopment;
$(document).ready(function () {
configureHostEnvironment()
....
}
In that method, configure the variables to use in production and development, like this:
function configureHostEnvironment(){
HOST = sessionStorage.getItem("ProductionHostURL")
if (HOST.length <= 0) {
alert("Host not configured correctly")
} else {
urlBaseProduction= host + '/api/';
urlBaseDevelopment= host + port + '/api/';
}
}
If you have a suggestion or improvement to this method, please comment.

Disable spaces in Input, AND allow back arrow?

I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?
$(function() {
var txt = $("input#UserName");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
fiddle: http://jsfiddle.net/EJFbt/
You may add keydown handler and prevent default action for space key (i.e. 32):
$("input#UserName").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
DEMO: http://jsfiddle.net/EJFbt/1/
This seems to work for me:
<input type="text" onkeypress="return event.charCode != 32">
It doesn't "disable" the back arrow — your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.
Simply don't do that.
Use a better mechanism for banning spaces, such as returning false from an onkeydown handler when the key pressed is space:
$(function() {
$("input#Username").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
});
This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.
Update
#VisioN's adapted code will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyup handlers that affect your textbox value whilst your caret is still active within it.
So here's the final code:
$(function() {
// "Ban" spaces in username field
$("input#Username").on({
// When a new character was typed in
keydown: function(e) {
// 32 - ASCII for Space;
// `return false` cancels the keypress
if (e.which === 32)
return false;
},
// When spaces managed to "sneak in" via copy/paste
change: function() {
// Regex-remove all spaces in the final value
this.value = this.value.replace(/\s/g, "");
}
// Notice: value replacement only in events
// that already involve the textbox losing
// losing focus, else caret position gets
// mangled.
});​​​​​
});
Try checking for the proper key code in your function:
$(function(){
var txt = $("input#UserName");
var func = function(e) {
if(e.keyCode === 32){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
That way only the keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.
If you're unsure about a certain keyCode try this helpful site.
One liner:
onkeypress="return event.which != 32"

action by key press

I'm designing a web based accounting software. I would like to open the "new accounting document" whenever the user press N key for example. And open "settings" whenever he/she is pressing S key.
I saw some scripts based on JavaScript and jQuery. But they did not work exactly. Can anyone help me please ?
I have tried this script:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
To prevent if an input is focused:
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });
You might want to put the bind function into its own function so you don't duplicate code. e.g:
function bindKeyup(){
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });
You can detech keypresses in jQuery using either .keypress() or .keyup() methods, here is a quick example :
$(document).keyup(function(event) { // the event variable contains the key pressed
if(event.which == 78) { // N keycode
//Do something
}
});
Here is a list of keycodes : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Update 1
.keyup and .keydown have different affects - as per comments from #ThomasClayson -: keyup is the best one to go for as keypress will repeat if the key is held down. it registers an event for each character inserted. It also doesn't register modifier keys such as shift (although not necessary here, it might be something to keep in mind)
Update 2
This is from the jQuery keyup doc site :
To determine which key was pressed, examine the event object that is
passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the key code. This
code corresponds to a key on the keyboard, including codes for special
keys such as arrows.
Affectively meaning that which.event is all you need to determine which key has been used. Thanks #nnnnnn
You need to read up on the .keyCode() attribute of the event object. You can interrogate that to discover which key was pressed and act accordingly. I'd also suggest you add modifier keys to your shortcuts, such as Shift or Alt, so that when someone is innocently typing in an input, the panel doesn't pop up. In the example below I've used Shift
$(document).keyup(function(e) {
if (e.shiftKey) {
switch(e.keyCode ? e.keyCode : e.which) {
case 78: // N pressed
myNPressedHandler();
break;
case 83: // S pressed
mySPressedHandler();
break;
}
}
}
$(document).bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keyCode==78) {
// "n"
}else if(keyCode==83) {
// "s"
}
});

How to REALLY limit the available character for an input field using jQuery?

I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).

Categories

Resources