how to find out keycode value of char in javascript - javascript

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

Related

jquery keydown bind with regex does not validate for apostrophe and periods

I have been using jquery to capture the keydown event and validate the entered text for different cases like: characters only, alpha-numeric, characters and spaces etc.
Regex used:
Characters with spaces: ^[a-zA-Z ]+$
Characters only: ^[a-zA-Z]+$
Alphanumerics: ^[a-zA-Z0-9]+$
This is how I am using the bind function:
$('.chars_and_space_only').bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
All of above uses cases are working fine, however I have to now include characters, spaces, apostrophe and periods. So this is the method I have modified:
$(".chars_space_dots_apostrophes_only").bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z '.]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
This, strangely doesn't seem to work. Here is the fiddle: https://jsfiddle.net/ugu8f4y3/
Regex used: ^[a-zA-Z '.]+$
Regex validator does validate this text for the above regex:
Hello. World's
But the text field in fiddle does not allow me to enter periods and apostrophes, is there something I am missing here?
The problem is with jquery and the keydown event. Replace it with keypress and you'll be good to go. You should also only need to check in which.
keydown and keyup are important for cases when you're concerned with the position of the key's physical location. In this case you want to know that the key was depressed and handle the resulting input. jquery will normalize the character codes differently.
Further information about the differences between keypress, keydown and key up.
Updated Fiddle

What is before and after keydown in Textarea?

I do not want to allow to press the function key like (F1,F2..etc),tabular key and also do not add any characters too.
for that one below code which is not working from my site.
document.getElementById("code").addEventListener("keydown",function(e){
var oldOne = this.value;
var newOne = (this.value + String.fromCharCode(e.keyCode)).toLowerCase();
if(oldOne==newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})
<textarea id="code"></textarea>
<div id="message"></div>
Because convert charcode that is out of available char range [32, 126] would produce a "", while it seems like a empty string, it accounts to length, and can't be trim like a space, so "apple" + "ctrl"' s length is 6 while it displays as "apple", you should better use
if (e.keyCode < 32 || e.keyCode > 126) {
// This is not a valid char, do something to ignore
}
to ignore those special chars, rather than convert it to string, append to current value then compare with oldValue.
When you're writing
String.fromCharCode(e.keyCode)
Then you're always getting a string even if you press though you're not seeing any change in the value, the String.fromCharCode(e.keyCode) is getting something, the string format of the key, it's not a blank string so you're always getting false in the if.
Either you can check in the keycode or you can check after keyup.
keydown event give you the state of object before your character is written.
`keyup events give you the state of object after it's written.
You may want to do something like this (fiddle):
document.getElementById("ta").addEventListener("keydown", function () {
this.oldValue = this.value;
});
document.getElementById("ta").addEventListener("keyup",function(e){
var oldOne = this.oldValue;
var newOne = this.value;
if(oldOne == newOne){
e.preventDefault();
}
document.getElementById('message').innerHTML = "Is it the same: "+(oldOne==newOne)+", Before: "+oldOne+", After: "+newOne;
})

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

Regex for negative decimal values client and server side c# jquery

I have a keypress function bound to an element, this element needs to only allow positive and negative decimal characters. i.e. 0-9, '.' , '-'
any other characters I need to prevent the character being inputted
Is there any way to achieve this in the current keypress function
$('.test').keyup(function (event) {
//if character is NOT ok i.e. 0-9, '.' , '-'
//STOP
..ELSE
//continue to do something
});
P.s. I am using jquery
One other way is to replace all illegal characters when typing:
$("selector").keyup(function (e) {
this.value = this.value.replace(/[^0-9\.-]/g, '');
});
May be useful, when user not typing text, but pasting it.
The key is inserted on keydown, so you should use that event instead. Then this should work:
$('.test').on('keyup', function(e){
e.preventDefault();
if(e.keyCode >= 48 && e.keyCode <= 57 // regular numbers
|| e.keyCode >= 96 && e.keyCode <= 106 // Numpad
|| e.keyCode === 189 // Minus
){
try{
parseInt($(this).val());
// Continue, this is a valid numeric value.
}catch(ex){
// Stop
}
}else {
// Stop
}
});
Hope this helps:
var string = '-10.56',
illegal = /[^0-9.-]/.test(string); // return true if illegal character found

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