key charCode for virtual keyboard - javascript

I have the below code to allow the user input only numbers, this works in browser. But when I access on mobile I think I am not able to get the right key code. So what are the keycodes for the same. Isn't same as the web.
// block e char, dot, hiphen and spacebar
if (event.key === 'e' || [46, 45, 32].includes(event.charCode)) {
event.preventDefault();
}else{
// allow to input logic
}
What are the charCode for dot, hyphen and space which will work for both web and mobile keypad ?

Your code is using event.charCode, which does not exist.
event.which.charCode does. Also you do not tell us what event.
There are keypress, keydown, keyup, input and some do not set some of the expected event values
Tested on Android and iOS using browserstack
Only one that seems to work in React on Android
export default function App() {
const handleInput = (event) => {
// eslint-disable-next-line
event.target.value = event.target.value.replace(/[e\.\- ]/g, "");
console.log(event.target.value);
};
return (
<div className="App">
<input type="number" onInput={handleInput} />
</div>
);
}
Older answers
Keydown and the code names which is recommended
document.getElementById("positiveIntOnly").addEventListener("keydown",function(e) {
// block e char, dot, hyphen and spacebar
if (["KeyE", "Period", "Minus", "Space"].includes(e.code)) {
event.preventDefault();
console.log(e.code);
}
});
<input type="number" id="positiveIntOnly" />
Or as mentioned by TJ, e.key:
document.getElementById("positiveIntOnly").addEventListener("keydown",function(e) {
// block e char, dot, hyphen and spacebar
if ("e.- ".includes(e.key)) {
event.preventDefault();
console.log(e.key);
}
});
<input type="number" id="positiveIntOnly" />
Set a min and max and use a regexp to handle paste
<input type="number" id="positiveIntOnly" min="0" max="999" step="1"
oninput="this.value = this.value.replace(/[e\.\- ]/g,'')" />

You can just you the key property:
["e" ,"E", "-", ".", " "].includes(e.key)
You're not supposed to use the charCode property as it is deprecated.

Related

HTML onkeypress works in HTML but not through JavaScript function on iOS

I have an input field which I want to restrict to only input numbers. type="number" works fine on computer and my android mobile but fails on iOS and I can still enter text in it. I looked around online and found this solution for the input field:
<input onkeypress="return event.charCode >= 48 && event.charCode <= 57" id="priceInput" type="text">
It works on all devices I have tried so far. However, I want to use this code for many input fields, and also do more things when pressing on a key in those input field. Therefore I want to run it as a JavaScript function in a separate file. I found this answer which looked promising and worked for android and desktop:
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;
}
<input type="text" onkeypress="return isNumber(event)" />
However, this still fails on iOS and I can still put in all characters.
Questions
How can I limit input field to only accept numbers on iOS phones?
Do iOS have some blocker for functions to run on onkeypress?
The snippet you find is quite old and uses the which and keyCode properties, which both are deprecated.
Instead use the code and / or key properties to determine which keyboard button has been pressed.
Note: with this method you'll have to whitelist every key that you want to be enabled for the input.
Since you're using a text input, consider using the inputmode attribute to force mobile users to use a specific keyboard, like a numeric keyboard which presents numbers.
const input = document.querySelector('input');
input.addEventListener('keydown', isNumber);
const allowedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Backspace'];
function isNumber(event) {
if (!allowedKeys.includes(event.key)) {
event.preventDefault();
}
}
<input type="text" inputmode="numeric" />
Edit: alternatively you could use the input event which is triggered based on changes in the value of the input. This event will fire regardless the manner of input (keyboard, mouse, etc.). The snippet below will replace anything that is not a number with an empty string while typing.
const input = document.querySelector('input');
input.addEventListener('input', isNumber);
function isNumber(event) {
event.target.value = event.target.value.replace(/[^0-9]/g, '');
}
<input type="text" inputmode="numeric" />
function isNumber(e) {
event = e.value;
if(event = ""){
console.log("empty")
}
return true;
}
<input type="text" onkeypress="return isNumber(event)" />

Handling both clicks and keypresses in React number input not working

I have part of some React code below, where I have a number input, I'd like to prevent people being able to click below 0, which I've done with the min attribute. However I've seen that it's possible to still manually key in negative numbers. After some googling I've seen that people can handle this with a keyPress check and looking at the character codes but for some reason I can't quite get this to work.
Are both handlers clashing with each other? My goal is to allow click increments to work for positive numbers and prevent negative and decimal numbers being allowed in the input.
It's a controlled input, where value is coming from state.
const handleChange = (e) => {
console.log(e.target.value);
setCount(e.target.value);
};
const handleKeyPress = (e) => {
console.log(e.target.value);
console.log(e.charCode);
if (e.charCode >= 48 && e.charCode <= 57) {
setCount(e.target.value);
}
};
return (
<section>
<h3>Input test</h3>
<form onSubmit={handleSubmit}>
<label htmlFor="amount">paragraphs:</label>
<input
type="number"
name="amount"
id="amount"
min="0"
value={count}
onKeyPress={handleKeyPress}
onChange={handleChange}
/>
You can format your value to absolute integer in your handleChange function and it would remove the zero and decimal separator on re-render:
const handleChange = (e) => {
setCount(Math.abs(parseInt(e.target.value)));
};
Or if you absolutely want to prevent "0" and "." characters to be entered, you can use preventDefault in your handleKeyPress function:
const handleKeyPress = (e) => {
if (e.charCode === 45 || e.charCode === 46) {
return e.preventDefault()
}
};
In this case you would like to use onKeyPress as a validator only. If validation fails, you can call e.preventDefault(). This way it will prevent to trigger onChange:
const handleKeyPress = (e) => {
if (e.charCode >= 48 && e.charCode <= 57) return
e.preventDefault()
};

How to block +,-,e in input type Number?

When I'm giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?
<input type="number">
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
// 0 for null values
// 8 for backspace
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
You can block entering those chars with keydown event
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.
What happens when you enter 1e is that, input field checks if it's a number, and if it's not (1e is not) it throws a warning:
The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
and the value property is set to "".
If you check the field's properties, you'll find valueAsNumber property. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1e is not a number, it evaluates to NaN, and NaN is assigned to valueAsNumber and value is set to "". Though you still see 1e on the input field.
I've asked a question related to this problem, but no solution yet.
Get the entered value on number input field, not the parsed
Instead on trying to block values, you can try to replace values that are non numeric.
If you choose to handle keycodes, you will have to handle numKeys, numPad, shift +, crtl + etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.
Also that way whatever you enter into the array will be prevented from being keyed in into the input box
Note - take the 'elementid' as the id of the element you want to apply this to
similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")
var invalidChars = ["-", "e", "+", "E"];
$("input[type='number']").on("keydown", function(e){
if(invalidChars.includes(e.key)){
e.preventDefault();
}
}):
This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.
UPDATE
Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.
Here's a pretty concise solution using jQuery based on some of the other solutions:
$("input[type=number]").on("keydown", function(e) {
var invalidChars = ["-", "+", "e"]; //include "." if you only want integers
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
You can do it easily using jQuery
Try this code
$(function() {
$("#input").keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
$(".alert").html("Enter only digits!").show().fadeOut(2000);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
You can check it if it's a number or not.
// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
if (isNaN(e.key)) {
return false;
}
});
Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:
angularjs: allows only numbers to be typed into a text box
JQuery
You can also use the following code if you want to accept decimals(.)
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key)!=-1){}
else if (e.key=='.' && this.value!='' && (this.value.match("\.") || []).length==0){}
else{e.preventDefault();}
});
Here is React solution, hope it will help somebody
const numberInputInvalidChars = ['-', '+', 'e'];
<input
type="number"
onKeyDown={(e) => {
if (numberInputInvalidChars.includes(e.key)) {
e.preventDefault();
}
}}
></input>
With onKeyUp, onKeyPress or onKeyDown events the same can be restricted.
onKeyDown = {
(e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
Yo can Block by using some JQuery codes
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key) == -1) {
e.preventDefault();
}
});
This will affect on all Numeric typed Input
I'm not sure the details of your use case, but you may not need to do a lot to handle these yourself. For starters, you can set a min, which can be used to prevent negatives, as well as a max value and a step value if that's useful. It turns out the default step is 1, so it requires integers unless you specify a decimal step value.
When it comes to dealing with the "e" in numbers, you can use Number() to convert text to a number, and it'll automatically convert the "e", as well as any "+" sign:
> Number("5e3")
5000
> Number("+42")
42
If you really need the submitted value to be normalized, you can convert it back in place. I think probably the most user friendly time to do it would be on blur:
input.addEventListener('blur', () => {
if (input.value !== '' && input.checkValidity()) {
input.value = Number(input.value);
}
});
in the input of numeric type the events for characters with value different from [0-9] is an object
with
event.target.value: ""
so just prevent events that have no value
if (!event.target.value) {
event.preventDefault();
};
If you want + sign in your phone number field then you can use this code.
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />

Restrict characters in input field

Is there a way to block users from writing specific characters in input fields? I tried the code below, but when a user enters disallowed characters, they appear for a brief period before disappearing. I want the input to remain unchanged when invalid characters are written.
I want to use onchange because other restriction methods do not seem to work on mobile devices. The problem I want to solve is that characters appear briefly before being removed.
function checkInput(ob) {
const invalidChars = /[^0-9]/gi;
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
};
<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
you can use try this,
$('.input').keyup(function () {
if (!this.value.match(/[0-9]/)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
SEE THIS FIDDLE DEMO
Updated :
You can try this Code,
$(document).ready(function() {
$(".input").keydown(function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
SOURCE
SEE UPDATED FIDDLE DEMO
UPDATED FOR ANDROID:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="#+id/textView1"
android:maxLength="1" >
</EditText>
I think it may help you... using android:inputType="number" you can do that.
A combination of keypress and paste events does a trick:
var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;
function checkInput(e) {
var e = e || event;
var char = e.type == 'keypress'
? String.fromCharCode(e.keyCode || e.which)
: (e.clipboardData || window.clipboardData).getData('Text');
if (/[^\d]/gi.test(char)) {
return false;
}
}
<input class="input" maxlength="10" id="text" type="text" autocomplete="off" />
This code prevents from typing or pasting anything but a number. Also no blinking and invalid characters don't show up.
Works in IE7+.
Demo: http://jsfiddle.net/VgtTc/3/
All answers given so far suffer from at least one of the following accessibility issues:
They validate key codes, which does not work with non-QWERTY keyboard layouts.
They do not cover all input methods; especially drag&drop is often forgotten.
They alter the value, which resets the position of the caret.
They use the pattern attribute, but this does not provide feedback until the form is submitted.
Wouldn't it be a much better idea to actually validate the input before it's inserted?
The beforeinput event fires before the input's value is changed. The event has a data property which describes the content that the user wants to add to the input field. In the event handler, you simply check the data attribute, and stop the event chain if it contains disallowed characters.
We end up with the following very simple, very short code.
const input = document.getElementById("input");
const regex = new RegExp("^[0-9]*$");
input.addEventListener("beforeinput", (event) => {
if (event.data != null && !regex.test(event.data))
event.preventDefault();
});
<label for="input">Enter some digits:</label>
<input id="input" />
Some closing notes:
Accessibility: Provide a clear explanation of what input format is expected from the user. For example, you can use the title attribute of the input to show a tooltip explaining the expected format.
Security: This is client-side validation, and does not guarantee that the pattern is enforced when the form is sent to a server. For that, you'll need server-side validation.
Here's a little hack you could try: DEMO
What it does is that it colors every input text white and then changes it back to black if it suits your requirements. If you could live with the bit of lag that occurs when you enter a valid character.
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
else {
document.getElementById('yourinput').style.color = '#000';
}
};
function hideInput(ob) {
document.getElementById('yourinput').style.color = '#FFF';
};
html
<input id="yourinput" class="input" maxlength="1" onKeydown="hideInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
css
input {color:#FFF;}
check this code,
$('.input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
​
<input id="testInput"></input>
<script>
testInput.onchange = testInput.oninput = restrict;
function restrict() {
testInput.value = testInput.value.replace(/[^a-z]/g, "");
}
</script>
I came up with something slightly different. oninput instead of onkeyup/onkeydown, and onchange instead of onpaste.
I restrict invalid characters on both keypress and paste events like:
<input type="text" onkeydown="validateKey(event)" onpaste="validatePaste(this, event)">
And define functions to handle these events inside tab or a separate javascript file:
<script>
function validateKey(e) {
switch(e.keyCode) {
case 8,9,13,37,39:
break;
default:
var regex = /[a-z .'-]/gi;
var key = e.key;
if(!regex.test(key)) {
e.preventDefault();
return false;
}
break;
}
}
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
</script>

is there a way to disable 'tab' on a input type='text'?

is there a cross-browser solution to disable 'tab' on a input type='text' ?
<input type='text' />
Pressing 'tab' moves you to the next 'focusable' component (for example a button)
I want instead 'tab' to do something else.
For example
Even in a google search tab is just used to autocomplete the suggested text instead of moving you to the next focusable component...
thanks
document.querySelector('input').addEventListener('keydown', function (e) {
if (e.which == 9) {
e.preventDefault();
}
});
Depends on how cross-browser you are talking though, as the above only supports IE9 (and other modern browsers).
http://jsfiddle.net/ExplosionPIlls/YVUzz/
IE8- use attachEvent instead of addEventListener and e.keyCode instead of e.which, and there is no preventDefault, but you can use return false.
a non jQuery implementation would be a bit like this -
HTML would be
<input type="text" id="myField1" onkeydown="return stopTab(event);" />
and JS something like below
function stopTab( e ) {
var evt = e || window.event
if ( evt.keyCode === 9 ) {
return false
}
}
Yes,check if the key pressed was tab, and if so, returns false:
<form class='noTab'>
<input type="text" />
<input type="text" />
<select>
<option>a</option>
<option>b</option>
</select>
<textarea>
</textarea>
</form>
jQuery('.noTab').find('input,select,textarea').keydown(function (e) {
if (e.which === 9) {
return false;
}
});
jQuery will allow this work on legacy browsers.
http://jsfiddle.net/JxMhY/
On that fiddle it shows 2 forms, one with the class "noTab" and one without, as tab/shift+tab are useful for many forms, but not the one which has a special "tab" action.

Categories