I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) {
alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
alert('input was a-z');
}
For a more dynamic check, use a regular expression:
const input = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(input)) {
alert('input was a letter, number, hyphen, underscore or space');
}
See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.
Use event.key and modern JS!
No number codes anymore. You can check key directly.
const key = event.key.toLowerCase();
if (key.length !== 1) {
return;
}
const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');
if (isLetter || isNumber) {
// Do something
}
You could also use a simple regex. ^$ ensures 1 char, i ignores case
/^[a-z0-9]$/i.test(event.key)
or individually:
const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)
First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
alert("Letter or number typed");
}
};
If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.
if (event.keyCode >= 48 && event.keyCode <= 90) {
// the key pressed was alphanumeric
}
For numeric values:
function validNumeric() {
var charCode = event.which ? event.which : event.keyCode;
var isNumber = charCode >= 48 && charCode <= 57;
if (isNumber) {
return true;
} else {
return false;
}
}
Here, 48 to 57 is the range of numeric values.
For alphabetic values:
function validAlphabetic() {
var charCode = event.which ? event.which : event.keyCode;
var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
var isSmallAlphabet = charCode >= 97 && charCode <= 122;
if (isCapitalAlphabet || isSmallAlphabet) {
return true;
} else {
return false;
}
}
Here, 65 to 90 is the range for capital alphabets (A-Z), and
97 to 122 is the range for small alphabets (a-z).
As #Gibolt said, you should use event.key.
Because charCode, keyCode and which are being deprecated.
To detect letters & numbers when using <input> or <textarea> you can use input event.
This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.
var element = document.getElementById('search');
element.addEventListener('input',function(e){
console.log(element.value);
});
<input id="search" type="text" placeholder="Search" autocomplete="off">
Simply you can add your Html forms in the input field like this:
...onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"
You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:
...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"
For number only:
...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"
Don't forget, to add for each input fields their own value.
<div class="form-group">
<input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address" autocomplete="false" onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"/>
</div>
$('#phone').on('keydown', function(e) {
let key = e.charCode || e.keyCode || 0;
// 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
// 127 - delete
if (key > 32 && (key < 48 || key > 58) && key !== 127) {
e.preventDefault();
return false;
}
});
modified answer of #user4584103, allows us to remove characters, and navigate in input box and filter out every not number character
You can also use charCode with onKeyPress event:
if (event.charCode > 57 || event.charCode < 48) {
itsNotANumber();
} else {
itsANumber();
}
number validation, works fine for me
$(document).ready(function () {
$('.TxtPhone').keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
// only numbers
if (key < 48 || key > 58) {
return false;
}
});
});
Accept numbers or letters with JavaScript by Dynamic Process using regular expression.
Add onkeypress event for specific control
onkeypress="javascript:return isNumber(event)"
function numOnly(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
function Alphanum(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
Use $.isNumeric(value); return type is boolean
$(document).ready(function () {
return $.isNumeric(event.keyCode);
});
A very simple, but useful method to try (i needed on a keyup event, letters only),
use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)
let typeOfKey = e.code.slice(0,-1)
if(typeOfKey === 'Key'){
console.log(typeOfKey)
}
Related
I'm attempting to capture all key events for my JQuery app. When using the keydown event, I'm able to get enter and tab events, but all letters are uppercase. So, I tried switching to keypress which I heard is lower + uppercase letters. This worked, except it wouldn't capture enter and tab events anymore. Is there a best of both worlds? How can I capture all events, case sensitive including keys like enter, tab, shift, alt, etc.
In key down event, call the method with event as a parameter and add this line,
e.preventDefault()
This will suspend the action.
Thanks,
How about doing this?
$(window).on('keydown keypress', function(e) {
e.preventDefault();
var code = e.keyCode || e.which;
console.log(code);
});
What this should do in theory is prevent the other event getting fired, but because we are calling both keydown and keypress, one of them will surely be fired. Now this can have negative effect on the rest of your code, so please use it carefully.
Hope this helps what you are try to do
$(document.body).on('keypress', function(e) {
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
if (valid) {
console.log(keycode + ' keypress'); //printable char on keypress
}
});
$(document.body).on('keyup', function(e) {
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
if (!valid) {
console.log(keycode + ' keyup'); //non printable char on keyup
}
});
got visible characters validation from this SO link
$(".num").keypress(function (e) {
console.log('[keypress] key' + e.key + ' keyCode' + e.keyCode + ' which' + e.which);
var kc = e.keyCode || e.which;
if (kc < 48 || kc > 57)/* number keys*/ {
//$.alertme('no');
if (e.preventDefault) {
e.preventDefault();
console.log('[keypress] preventDefault');
} else {
e.returnValue = false;
console.log('[keypress] returnValue');
}
}
//$.alertme('ok');
//var re = /[0-9]/.test(e.key);//not working android browser
//if (!re) {
// if (e.preventDefault) {
// e.preventDefault();
// } else {
// e.returnValue = false;
// }
//}
});
check for only number
add num class to input text
I want my JQuery code to only accept numbers as input in the textfield, this code is working well for me but soon discovered that if I used the numbers in my numpad it does not work. Any suggestions for this problem guys?
Here is my code:
<script type="text/javascript">
$(".txtboxToFilterNum").keydown(function(event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 0 || event.keyCode == 13 || event.keyCode == 27) {
// let it happen, don't do anything
}
else {
// Ensure that it is a NUMBER and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
</script>
Do not check which key is pressed, but which content is given, it will be easier to check if the content are numbers only, and it will prevent many other things such as using copy and paste with letters (I guess this is not handled in your given code too)
working sample
HTML
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
Javascript
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 do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?
As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters.
for example: limitCharacters(textid, pattern)
You can just check the keyCode on keydown and run preventDefault() if match:
$('input').keydown(function(e) {
if (e.which == 8) { // 8 is backspace
e.preventDefault();
}
});
http://jsfiddle.net/GVb6L/
If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:
$.fn.restrict = function( chars ) {
return this.keydown(function(e) {
var found = false, i = -1;
while(chars[++i] && !found) {
found = chars[i] == String.fromCharCode(e.which).toLowerCase() ||
chars[i] == e.which;
}
found || e.preventDefault();
});
};
$('input').restrict(['a',8,'b']);
http://jsfiddle.net/DHCUg/
I did something like this but in jQuery plugin format. This example will only allow numbers and full stops.
You can call this by writing:
$("input").forceNumeric();
And the plugin:
jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}
I would suggest using David solution for modifier keys like backspace and delete and this code below for characters:
var chars = /[,\/\w]/i; // all valid characters
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
});
Also, I've experienced some problems with keydown so I'd do it on keyup.
Demo: http://jsfiddle.net/elclanrs/QjVGV/ (try typing a dot . or semicolon ;)
I have this code, but somewhy when i use this function to validate my input field everything works, except + and - keys, even thought i noted them as true. What have i done wrong?
function validateNumber(event)
{
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 107 || event.keyCode == 109 ||
event.keyCode == 32 )
{
return true;
}
else if(key < 48 || key > 57)
{
return false;
}
else return true;
};
I don't see you checking for 189 (-) and 187 (=, which is really what happens when you type +). You might want to check if the Shift key is pressed for +.
As already noted, it's overall a wrong way to validate user input. You need to inspect the value of the input, not individual keystrokes.
First, define a validation function that would check an arbitrary text with a regexp:
function checkArithmetic(str) {
var regexp = /^[0-9+-]$/;
return regexp.test(str);
}
Next, add a handler to your input element:
input.addEventListener('input', function (e) {
var value = input.value;
if (checkArithmetic(value)) {
// OK!
} else {
// error
}
}, false);
I have written a JS function that only allow numbers to be entered. A copy of that function is below:
function NumbersOnly(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
//Allow tab, backspace and numbers to be pressed, otherwise return false for everything.
//(keyCode>=96 && keyCode<=105) are the numpad numbers
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
}
This function works fine with all the numbers but my problem happens when the shift key is held down and one of the number keys is pressed. The value returned is one of the characters above the numbers. So for example if I hold down shift and press 7, '&' is returned but the keyCode is still 55!! I would have expected that to be different.
So my question is how do I check if the shift key is being held down.
I've tried the following check but this didn't work:
if (keyCode === 16) {
evt.returnValue = false;
}
else {
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
I'm using ASP.NET 4.0.
Any help would be gratefully received.
Thanks in advance.
You can check if shift key is pressed using :
if(evt.shiftKey) {
... //returns true if shift key is pressed
Use event.key instead of charCode. No more magic numbers!
function onEvent(event) {
const key = event.key; // "a", "1", "Shift", etc.
if (isFinite(key)) { // Is number
// Do work
}
};
Mozilla Docs
Supported Browsers
use keypress for holding any key isntead of keydown