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
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 am trying to allow only numbers [0-9] to be typed in a text box. If an alpha or special character is typed, I do not want it to be shown in the text box. Currently my code is as follows:
$('#TEXTBOX').on("keydown", function(event){
var keyCode = event.which;
if(!((keyCode > 47 && keyCode < 58) || (keyCode > 95 && keyCode < 106) || keyCode == 08)){
event.preventDefault();
}
});
I am having a few problems.
This function is still allows special characters [i.e (SHIFT + 1) gives !, (SHIFT + 2) gives #] I do not want these key combinations to allow insert into text box
I am using magic numbers. I would prefer not to use magic numbers and logic but this is the only way I was able to get the input validation to work.... are there any suggestions on other methods?
My main concern is my first problem with the special characters.
$('#TEXTBOX').on("keydown", function(event){
var keyCode = event.which;
var charCode = (event.charCode) ? event.charCode : ((event.keyCode) ? event.keyCode: ((event.which) ? evt.which : 0));
var char = String.fromCharCode(charCode);
var re = new RegExp("[0-9]", "i");
if (!re.test(char))
{
event.preventDefault();
}
});
Use as
$('#TEXTBOX').on("keydown", function(event){
if(event.shiftKey)
return false;
var keyCode = event.which;
if(!((keyCode > 47 && keyCode < 58) || (keyCode > 95 && keyCode < 106) || keyCode == 08)){
event.preventDefault();
}
});
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// 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();
}
});
});
Worked For me (Only Numbers are allowed)
var key = e.charCode || e.keyCode || 0;
alert(key);
if (key < 48 || key > 58)
return false;
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 use the following to restricts user to enter only some characters.
When I press tab, the cursor does not point to next control (in Mozilla). But it works fine in IE.
// Restricts user to enter characters other than a to z, A to Z and white space( )
// Rauf K. 06.11.2010
$("input:text.characters_only").keypress(function(e) {
if (!((e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) || e.which == 32 || e.which == 8 || e.which == 9)) {
return false;
}
});
I would recommend trying e.keyCode instead of e.which. Here is a SO link that describes a good method of getting the key strike into a single variable regardless: jQuery Event Keypress: Which key was pressed?
Perhaps if you start with something like:
if (e.keyCode === 9) { // TAB
return true;
}