JQuery to allow only numeric input in text box using key code - javascript

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;

Related

JQuery keypress vs keydown event for capturing all keys

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

Restrict to numeric values rather than integer values

How do I restrict input fields to numeric values rather than integer values?
<input type="text" class="numericOnly">
jQ
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
Try this
$(".numericOnly").keypress(function(e) {
var code = e.which;
if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 51) || (code == 8) || (code >= 37 && code <= 40))
{
return true;
}
return false;
})
.bind("paste",function(e) {
e.preventDefault();
});
If you want to allow decimal points, add them to the character class you're using. E.g. /[^0-9.]/g if a decimal point in your locale is ., or /[^0-9,]/g if it's , (as it is in some).
Of course, that would let someone type .0.0.0.1, you'll want whole-value checks on the field as well as keystroke-level checks.
Separately, remember there are lots of ways for values to get into fields other than typing (pasting, for instance), so (again) whole-value checks at some stage will be a good idea.
Side note: Use e.which, not e.keyCode. jQuery normalizes the event object, setting e.which on browsers that don't set it natively.
With Dot
Get this js file
http://thefitties.co.uk/js/plugins/jquery-numeric.js
And
In HTML
<input class="numeric" type="text">
in Script
$("input.numeric").numeric()
WITHOUT DOt
$(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
(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();
}
});
});
OR
http://jsfiddle.net/lesson8/HkEuf/1/

Why my condition is not satisfied?

I have a textbox and i want to allow users only enter 4 digits as i want to take time from the user, but i am facing the strange problem in condition.
Fiddle Demo
Javascript
function CheckLength(val, key) {
var keycode = (key.which) ? key.which : key.keyCode;
if(!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57))
return false;
if (val.length < 4)
console.log(val);
else
return false;
}
HTML Markup
<input type="text" id="timepick" onkeyup="return CheckLength(this.value,event);" />
Can anyone help me? why this is happening?
Thanks for your precious time.
You could listen for a "keydown" event instead of "keyup" Heres your Fiddle, (i only changed up to down). , or remove the last entered key by resetting the value in the "keyup" event.
document.getElementById("timepick").addEventListener("keyup", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (e.target.value.length <= 4) console.log(e.target.value)
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) || e.target.value.length > 3)
e.target.value = e.target.value.substr ( 0,4)
});
Like in this Fiddle
Or you could use 2 seperate events, one "keydown" to prevent the input, and a keyup to read the value
document.getElementById("timepick").addEventListener("keydown", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (!(keycode == 8 || keycode == 46) && ((keycode < 48 || keycode > 57) || e.target.value.length > 3) e.preventDefault()
});
document.getElementById("timepick").addEventListener("keyup", function (e) {
if (e.target.value.length == 4) console.log(e.target.value)
});
Like in this Fiddle
Update, regarding your comment
You could, of course use only a "keydown" event, and build the value you want on your own.
document.getElementById("timepick").addEventListener("keydown", function (e) {
var keycode = (e.which) ? e.which : e.keyCode;
if (!(keycode == 8 || keycode == 46) && ((keycode < 48 || keycode > 57) || e.target.value.length > 3)) e.preventDefault()
if (e.target.value.length == 3) console.log(e.target.value + String.fromCharCode(keycode))
});
Like in this Fiddle
Hope this helps you. It prevents more than 4 values and shows the 4 entered into the log (in the fiddle I change the console.log by an alert).
I solved it by storing the 4 values into a variable and if the user enters more than 4 values restore the textbox value with the variable value:
http://fiddle.jshell.net/6czXu/7/
var vals;
function CheckLength(val, key) {
var keycode = (key.which) ? key.which : key.keyCode;
if (val.length < 5){
alert(val);
// Here store the 4 values
vals = val;
if((keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57))
return false;
}
else{
// Here we have more than 4 digits entered so
// we restore the prevously stored into vals
document.getElementById("timepick").value = vals;
return false;
}
}
Use the onkeypress event instead and everything should work fine. onkeyup is to late.
<input type="text" id="timepick" onkeypress="return CheckLength(this.value,event);" />

event.keycode issue

i have a javascript code like below,
if (event.keycode != 37 && event.keycode != 39)
{
var phoneNumber = $('#phoneNumber').val();
if (phoneNumber.length < 1 && event.keyCode != 48)
$('#phoneNumber').val(0)
else if ((phoneNumber.length < 2 && event.keyCode == 48) )
event.preventDefault();
else
$('#phoneNumber').val(phoneNumber)
}
keycode 37 = left arrow, keycode 39 = right arrow but when i pressed these keys on keyboard condition which is between if block being executed, i am using chrome browser, also i used the if statement below,
if (event.keycode != 37 || event.keycode != 39)
{
var phoneNumber = $('#phoneNumber').val();
if (phoneNumber.length < 1 && event.keyCode != 48)
$('#phoneNumber').val(0)
else if ((phoneNumber.length < 2 && event.keyCode == 48) )
event.preventDefault();
else
$('#phoneNumber').val(phoneNumber)
}
urgent helps greatly appreciated,
Thanks everybody.
One issue is capitalization: it's keyCode, not keycode. Your code is using them inconsistently.

using jQuery/javascript to restrict price field input

I found the following jQuery code on the internet, but I soon found that it had a deficiency in that it dit not accept a decimal point (ascii code 46) - even though the code appears to allow it.
Currently, I cannot enter prices like 1.23, since the the period is ignored and I get 123 instead.
Can anyone spot whty this is not working?
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
I am using the plugin like this:
$(function(){
$('#price_field').ForceNumericOnly();
});
The other users have pretty much answered your question already, but I wanted to provide you with this link.
http://unixpapa.com/js/key.html
I found it quite useful when dealing with keyboard events and making them cross-browser compatible.
I hope this helps.
Just add the . (code 190 and 110) to the checks:
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 190 || // normal .
key == 110 || // keypad .
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You should add the key code 190 to accept "."
// Numeric only control handler
$.fn.ForceNumericOnly = function() {
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow dot, backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 ||
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You need to include 190 and 110 for both decimal points.
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 || //add this line. 190 is the keycode for a period
key == 110 || //and this line. 110 is the keycode for a decimal
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};

Categories

Resources