Extending function syntax explanation - javascript

Hello I found js function that is called when onkeypress event of textBox fires. I'am asking if some one could explain its syntax.
function isDecimalKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if(charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) return false;
return true;
}
I'm not certain what this var charCode = (evt.which) ? evt.which : event.keyCode bit of code means but I want to extend this function so it will also check if number is in allowed range that is max value 999.9 min value 0.0. number can have only 1 decimal place so it cant be 1.123.
Suming up: Value can have maximum 5 characters including "." for decimals, and maximum 1 decimal place.

Its just the ternary operator which basically says
(is this expression true) ? -> YES DO THIS : NOPE, ITS NOT DO THAT INSTEAD
In this instance, you could easily replace the line by just using logical OR
var charCode = evt.which || event.keyCode;
Basically this is the same check. If evt.which has any truthy value the interpreter will ignore the right side expression. If the first expression evaluates to false, we use the rightside expression regardless what it contains.

Related

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.

Not allowing to add or update any numeric or decimal value once it reach upto two decimal

I need to restrict the user for following things:
1) only allow numeric
2) decimal upto 2 digits
3) allow - backspace, tab,delete buttons
Below code is working fine except one scenario,
Problem is, (Example) when textbox input reach as 6545.12 then after try to change the value as below 65457.12 or 7545.13 then it does not allow and just restrict me. (so, here, not allowing to add new digit or change the existing digit before . or after .)
Can any one please guide me how to solve this issue.
calling below function on keypress event of textbox.
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (
&& // “-” CHECK MINUS, AND ONLY ONE.
(charCode != 8) && (charCode != 9) && (charCode != 37) && (charCode != 39) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)) {
return false;
}
if ($(element).val().indexOf('.') != -1)
{
var index = $(element).val().indexOf('.');
var len = $(element).val().length;
var CharAfterdot = (len + 1) - index;
if (CharAfterdot <= 3) {
return true;
}
else {
return false;
}
}
return true;
}
You might consider including a library that implements input masking (that is, only allowing certain kinds of values to be entered into an input field). Using a library like https://github.com/RobinHerbots/jquery.inputmask you can specify a regular expression as a mask. An example regular expression that only allows numbers up to two decimal places would be [0-9]+(\.[0-9][0-9]?)?. After including the masking library you can either call the mask directly on the element or add a data-inputmask-regex property to your input. See https://github.com/RobinHerbots/jquery.inputmask#usage for more.
Short version: this is a hard problem and other people have already done the work.

Only allowing certain characters

I am in the process of creating a form and I wish to validate the input fields onKeyPress. I have managed to find JavaScript to restrict a field to only allowing numbers to be entered. Now I am trying to adapt that code to only allow letters and a hyphens to be allowed.
The code I have to only allow numbers is as follows...
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
How would I adapt and change this to only allow letters and hyphens instead.
Sorry if this question has been asked before but all I can find is doing it using Jquery etc. and I would like to try and avoid that if I can.
Thanks in advance
var myRegex = /^[A-Za-z\-]+$/;
myRegex.test('hello'); //true
myRegex.test('asdasd-adasd'); //true
myRegex.test('123as'); //false

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

JS: Recognize dot or delete in keypress

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;

Categories

Resources