Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example
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" />
I wanted to know a way to allow only numbers and multiple dots in using jquery in a form input.
The scenario is that the form input holds a version name and version name can have values like 6.0.2345 and as far as my research went, I could get only the numbers working by the following code:
$('.number').keydown(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/do
});
But this allows only numbers and does not allow me to use backspace or delete. Any workaround from this method that I can use so that I can allow only multiple dots and numbers in the input file.
Finally arrived at this answer which works.
$(".submit").on('click',function(e){
e.preventDefault();
var test_val = $(".test").val();
var test_regex = /^(\*|\d+(\.\d+){0,3}(\.\*)?)$/i;
if(!test_regex.test(test_val)){
alert("This is not a valid entry");
}
});
<input onKeyPress={(event) => { if (!/[0-9.]/.test(event.key)) { event.preventDefault(); } }}
I am using google virtual keybord and set on the textarea.
When I write something on textarea so in a textarea they print two character one was uppercase and second was lowercase.
I write a JavaScript function for textarea in which after "." - dot those character is make it automatically capital Alphabet.
How I can remove a one character and textarea print just only one character? Because when I press single key they print two character.
this function iam using for uppercase after the "." dot and set up keypress event on textarea.
function caps(e, textarea, value){
//debugger;
var unicode=e.keyCode? e.keyCode : e.charCode;
var str=value.trim();
str=str.charAt(str.length-1);
if((str=="." || value.length==0) && (unicode>=97 && unicode<=122)){
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
return false;
}
return true;
}
To stop the default behaviour of an event, you can use e.preventDefault();. So something like
function caps(e, textarea, value){
//debugger;
var unicode=e.keyCode? e.keyCode : e.charCode; //my keyboard threw out ascii..
var str=value.trim();
str=str.charAt(str.length-1);
if(str=="." || value.length==0){
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
e.preventDefault();
}
}
input.addEventListener("keypress",function(e){
if(e.keyCode==8) return true
caps(e,input,input.value)
},false)
You could use return false, but you need to do something like
input.onkeypress=function(){
if(e.keyCode==8) return true
return caps(e,input,input.value); //pass false from caps too event
}
Demo
If I understand correctly, it seems you just need to remove the last character before adding the new one. Therefore something like this should work (it's untested though).
if((str=="." || value.length==0) && (unicode>=97 && unicode<=122)){
/*remove last character before adding new one*/
textarea.value = textarea.value.substring(0, textarea.value.length - 1);
textarea.value=textarea.value+String.fromCharCode(unicode).toUpperCase();
return false;
}
Although, depending on how this function is being called, you may be able to prevent the character being printed in the first place.
Sorry, realised you did say in the question title that it's the keypress event. In which case, e.preventDefault is your friend as shown in another answer. You can just replace your return false with it.
Hi could someone help me figure out how to stop a function running until a specific number of characters are pressed?
currently using the following function:
$('input#q').keyup
this works as soon as you press any key...
Something like this should start firing code after 3 letters have been added:
Live Example
JavaScript
$('input#q').keyup( function() {
if( this.value.length < 4 ) return;
/* code to run below */
$('#output').val(this.value);
});
HTML
<input id="q" />
<br /><br />
<input id="output"/>
you could do :
$('input#q').keyup(function(){
if($(this).val().length > 3)
{
//do something
}
});
You could store the characters in a string variable each time a key is pressed and then run a conditional statement to check the length of the variable. If it's equal to three, run whatever function
Well you'll probably need to take into account the way focus changes. Do you want to clear the counter when the field is newly focused or not? You should also decide whether you're counting characters actually added to the field, or instead if you want to could actual discrete key presses - a "shift" key press, for example, won't add any characters, but it's a key being pressed.
Anyway it'd probably be something like this:
$(function() {
var keyCount = 0;
$('#q').keyup(function() { // "keypress" to count characters
if (++keyCount === 3) {
// do the thing
}
})
.focus(function() {
keyCount = 0; // if this is what you want
});
});
If you're counting the "keypress" event instead of "keyup", you might want to count the actual length of the text field value rather than trying to count events.
How's about:
var c = 0;
('input#q').keyup( function() {
c++;
if (c >= 3) {
startGame();
}
} );