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?
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
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.
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">
$("#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>
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
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>