JS: Recognize dot or delete in keypress - javascript

I'd like to execute some code if the user presses the dot (on standard keybord or on numblock). But if I take it over Keycode (110), this is the same like the delete button.
How do I recognize them?
Thanks for your help!

Delete key (usually above arrows) is 46, numpad decimal is 110, and the keyboard period is 190.
This is a pretty good page to know what keycodes are what: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
If this doesn't answer your question, please rephrase it as it's a little confusing what you are looking for.

Use modern JS!
Use event.key === "." || event.key === "Delete", rather than arbitrary number codes!

it's only allow dot and numbers
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46 ) {
return false;
}
return true;

Related

keycode for numerics only | javascript

I have this piece of code. According to keycodes here
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html
this code should work but for some reason I am getting these characters as true.
eiadfghcb.
function validate(event) {
var keycode = event.keyCode;
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
return false;
}
}
html:
<asp:TextBox ID="txtImp" runat="server" Height="23px" Width="80" onkeypress="return validate(event)" onkeyup="calc()"/>
The following code should work for you:
function validate(event) {
var code = event.code;
if (typeof code !== "undefined") {
var
codeBeginning = code.substr(0, code.length - 1);
if (code === "Period" || code === "NumpadDecimal" || code === "Backspace" || ((codeBeginning === "Digit" || codeBeginning === "Numpad") && !parseInt(code.substr(code.length - 1)).isNaN())) { // key pressed is one of the "."-keys, the "Backspace"-key or one of the number-keys.
return true;
}
return false;
}
var keyCode = event.which || event.keyCode;
if (keyCode === 8 || keyCode === 46 || (keyCode >= 48 && keyCode <= 57)) {
return true;
}
return false;
}
Explanation regarding to why your code didn't work.
The first condition in your if-statement !(keycode == 8 || keycode == 46) will indeed evaluate to true when the key pressed is neither the decimal point-key or the BACKSPACE-key.
However the second and third condition will conflict with one another. This can be show by the following example:
The user presses the Numpad 2-key which (in my case) results in 50. This value does comply to the second condition as 50 is both higher than 48 and lower than 57, but it will not comply to the third condition as 50 is lower than 96.
As both the second and third condition will have to result to true and there is always one of the two that will result in false the code will never do what you intend it to do.
Disclaimer
My previous answer stated that KeyBoardEvent.keyCode is unreliable and resulted in an inability to capture the right keys on my machine.
Even though I'm now unable to reproduce this issue I would still advice you to only use KeyBoardEvent.keyCode when absolutely necessary (as the documentation of KeyBoardEvent.keyCode does state that it is implementation specific), and use KeyBoardEvent.which whenever possible.
Explaination regarding to why my code works.
As the KeyBoardEvent.keyCode relies heavily on the browser implementation thereof, I've chosen to using it as much as possible by instead using KeyBoardEvent.which.
However as both of these properties have become deprecated I've also used KeyBoardEvent.code to make sure that the solution adheres the lastest KeyBoardEvent specification.
As such my solution uses KeyBoardEvent.code when available as it isn't deprecated or implementation specific. If KeyBoardEvent.code is unavailable it uses KeyBoardEvent.which as it is more consistent that KeyBoardEvent.keyCode. And finally if KeyBoardEvent.which (as is the case in older browsers e.g. Internet Explorer 8) it will have to use KeyBoardEvent.keyCode.
The issue:
Take a look at your third condition:
keycode < 96 || keycode > 105 //Where keycode is NOT between 96-105
Now look at the ASCII codes for the characters you entered:
a: 97
b: 98
c: 99
d: 100
e: 101
f: 102
g: 103
h: 104
It should now be obvious why your code is failing - You've included a condition that very specifically ignores the characters you're claiming "don't work".
keyCode vs charCode:
When it comes to keyCode, you're going to run into some cross-browser issues. For that reason you may want to consider checking both keyCode and/or charCode, as each works in a specific set of browsers. A simple way to be sure we're getting a value that's consistent is to do something like this:
var keycode = event.keyCode || event.charCode;
In the event that event.keyCode won't work, charCode will be used instead.
The solution:
If you simply want to ignore the condition that I pointed out as the problem, then just remove it:
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
return false;
}
That being said, your question doesn't say what your desire is... at all. It simply says that what you have "doesn't work for the characters mentioned".
Additional info:
As a side note, I'd be remiss if I didn't point out that your code is not exactly... friendly, for lack of a better word. An elegant way of resolving this is to replace condition lists with named functions, so the purpose and result is much more discernible, like so:
Bad:
if (sunny || not raining and warm || not(cloudy and raining) || not cold)
Good:
if (weatherIsNice(...))
Applied in your case it may be something like
function characterIsAllowed(keycode) {
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
return true;
} else {
return false;
}
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
if (characterIsAllowed(keycode)) {
return false;
}
}
Or, simplified one step further...
function characterIsAllowed(keycode) {
return (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105))
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
return !characterIsAllowed(keycode);
}

How to disable typing special characters only not up, down, left and right keys?

I need enable 0 to 9 also up, down, left, right, delete, tab, home, end and etc like (alt, ctrl)
Need Chrome and Firefox browsers
$('.commonNumber').keypress(function(event){
var nbr = event.charCode ? event.charCode : event.keyCode;
// Numbers 8 -> Backspace 9-> Tab
if ((nbr >= 48 && nbr <= 57) || nbr == 8 || nbr == 9 || nbr == 37 || nbr == 38 || nbr == 46 || nbr == 39 || nbr == 40){
return true;
} else {
return false;
}
I enable 37, 38, 39,40,46 this codes are left, up, right, down areo and delete button keys but this keys are also %&('. keys using the same code. so this keys are enabled
});
Your code for normalizing the character code is incorrect. See the bottom of this answer as to why.
If you are using JQuery, it normalizes the which property for you, so you should use event.which to examine the pressed key. The event.which property will be less than 32 for non-printable characters. Therefore, you should always ignore the key when event.which is less than 32. Otherwise, check if it is a character you want to accept.
I also think you should allow the rejected key events to bubble, so use event.preventDefault() to reject a key, rather than return false.
$('.commonNumber').keypress(function(event) {
var charCode = event.which;
if ((charCode >= 32) && ((charCode < 48) || (charCode > 57))) {
event.preventDefault();
}
});
jsfiddle
The code above will limit the accepted printable characters to just numeric digits, while still letting the arrow keys, the delete key, the backspace key, and other control keys to work. Key events will also bubble up, so when the Enter key is pressed, it will still submit the form (if the input element is part of a form).
If you are not using JQuery to handle the keypress event, you have to normalize the event properties yourself. According to this stackoverflow answer, you should do:
var charCode = (typeof event.which == 'number') ? event.which : event.keyCode;
Apparently all browsers, except IE<=8, support the event.which property. In IE<=8, the event.keyCode property holds the Unicode reference number for a printable key instead.
The issue with your original code is that in most browsers (other than IE<=8):
event.charCode is the Unicode reference number of the character for printable keys, and 0 for non-printable keys.
event.keyCode is a system and implementation dependent numerical code. (This is often 0 for printable keys.)
For instance, in Firefox you get:
Ampersand key: event.charCode = 38 and event.keyCode = 0.
Up arrow key: event.charCode = 0 and event.keyCode = 38.
Block or restrict special characters from input fields with jQuery.
You can either return false or call preventDefault() method on event variable.
//this script allows only number input.
$(document).ready(function(){
$("#age").keypress(function(e){
var keyCode = e.which;
/*
8 - (backspace)
32 - (space)
48-57 - (0-9)Numbers
*/
if ( (keyCode != 8 || keyCode ==32 ) && (keyCode < 48 || keyCode > 57)) {
return false;
}
});
});
//this script Not allowing special characters
$("#name").keypress(function(e){
var keyCode = e.which;
/*
48-57 - (0-9)Numbers
65-90 - (A-Z)
97-122 - (a-z)
8 - (backspace)
32 - (space)
*/ // Not allow special
if ( !( (keyCode >= 48 && keyCode <= 57)
||(keyCode >= 65 && keyCode <= 90)
|| (keyCode >= 97 && keyCode <= 122) )
&& keyCode != 8 && keyCode != 32) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type='text' id='name' placeholder='Enter your name'><br/><br/>
<input type='text' id='age' placeholder='Enter your age'>
</div>

Allow AlphaNumeric and other symbol using JavaScript

I have use this code for allow numeric only in textbox, but how make Charkey only allow AlphaNumeric and other symbol like -./ (dash,dot,slash)
this my code for allow Numeric
function NumericKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
thankyou
Firstly, Character Codes and Key Codes are different thing, what you're looking for is Key Codes.
You can first check the key codes you want to allow/disallow by looking them up in a online table, or here: http://keycode.info/
Then then by using a whitelist/blacklist to check the codes:
function NumericKey(evt){
var allowed = [189, 190, 191]; // corresponds to **. , -**
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return allowed.indexOf(charCode) >= 0;
return true;
}
This would allow you to arbitrarily whitelist any keycodes.
A simpler solution to your case, since key codes of ,.- are adjacent to each other:
function NumericKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode >= 189 && charCode <= 191))
return false;
return true;
}
You should not listen for keyboard events (keydown / keypress / keyup) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.
Moreover, that won't work on mobile, where most keys emit the same values e.key = 'Unidentified', e.which== 229 and e.keyCode = 229.
Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:
const input = document.getElementById('input');
input.oninput = (e) => {
const cursorPosition = input.selectionStart - 1;
const hasInvalidCharacters = input.value.match(/[^0-9 -./]/);
if (!hasInvalidCharacters) return;
// Replace all non-digits:
input.value = input.value.replace(/[^0-9 -./]/g, '');
// Keep cursor position:
input.setSelectionRange(cursorPosition, cursorPosition);
};
<input id="input" type="text" placeholder="Digits and - . / only" />
Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993
Anyway, if you still want to try that approach, just keep in mind both e.which and e.keyCode are deprecated, so e.key or e.code should be used instead, which also makes the code easier to understand. Also keep in mind some old browsers used some non-standard codes for some keys, so, for example, left is usually 'LeftArrow' and right is 'RightArrow', but on IE and Legacy Edge they would be 'Left' and 'Right' instead.
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!
Disclaimer: I'm the author.

i need to void dot(.) form user key press is not working

This is my jquery it is avoid all the symbols and alphabet but it allow a dot (.) i don't know why someone help me please. . .
$('.Number').keypress(function (event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 27 || keycode == 9 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
return false;
}
else {
return true;
}
});
You would have better to use a regex for that kind of check:
DEMO jsFiddle
$('.Number').keypress(function (event) {
if(!/\d/.test(String.fromCharCode(event.which))) return false;
});
According to: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes the correct keycode for . (period) is 190 (or 110), and you have not added this to your list.
Note that browser implementations (and thus results) may vary and I have no idea the effect of regional keyboard settings on these keycodes.
Because you haven't added the keycode for decimal point.
110 for . for full stop
190 for decimal point

Javascript keycodes not working in firefox but works well in chrome

I'm just doing my form validation wherein which Phone number has to be only numbers! The code works well in chrome but not in firefox and IE. pls give me some solution
My code is as follows
function noLet(event) {
if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode < 58) {
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
HTML:
onkeypress="noLet(e)"><label id="mobph"></label><font
size="1"><br>Max 10 numbers only allowed!</font>
May i suggest the following code to solve your problem. This is what i am doing. Tested and works like a charm in ie, chrome and firefox:
//return numbers and backspace(charCode == 8) only
function noLet(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >= 48 && charCode <= 57 || charCode == 8)
return true;
return false;
You can use the key/char code to detect whether the key pressed is a number or not a number. First you have to detect what the key/char code is cross browser (remember to use event.keypress as your event to further assure compatibility). Afterwards, you convert it from its decimal value to its character. Then you can parse it as an integer using parseInt() which will return NaN if the first value inside the function cannot be parsed as an int. And then prevent the default action if it is NaN.
var numbersOnly = function(e){
var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
chr = String.fromCharCode(charCode);
if(isNaN(parseInt(chr, 10))) e.preventDefault();
}
<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">
Because on Firefox, at least, it's charCode, not keyCode in the keypress handler, and "returnValue" is ignored (invoke preventDefault() to stop the insertion).
There's compatibility issue of browsers. Here is a solution which I found out in some RND. Hope so it'll help you somehow; Click Here

Categories

Resources