Reputation: 51
I am confused why I am not able to use the 10 key to input numbers.
The following example auto fills the "/". I tried a few different ways to adjust the regex on it, but when I do, I can't backspace or delete anything past the last "/". (01/01/2000 ... 01/01/ <- won't let me delete past this).
$('#date').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$date = $(this);
if (key !== 8) {
var regex = new RegExp("^[0-9\t/]");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if ($date.val().length === 0) {
$date.val($date.val() + '');
}
if ($date.val().length === 2) {
$date.val($date.val() + '/');
}
if ($date.val().length === 5) {
$date.val($date.val() + '/');
}
}
});
Please help me find a way where it continues to auto-format the "/" as it does now but restricts to numbers only (except the required "/") and allows me to use the 10 key numbers.
Any help would be greatly appreciated.
Thank you in advance.
Upvotes: 0
Views: 1709
Reputation: 584
if you want allow only number and ignore any key : use this code in JavaScript tag:
$('*[data-validation="digit"]').keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
and any input that you want apply this role add this attribute :
data-validation="digit"
for example :
<input data-validation="digit" />
I recommend you Use a Masked Input plugin eg: Masked Input plugin for jQuery
for example for date :
$("#date").mask("99/99/9999",{placeholder:"mm/dd/yyyy"});
in this plugin you can combination of word and number or any characters
Upvotes: 2
Reputation: 3872
You're not checking for backspace properly. Check your value of 'key'.
I think it should assigned as followed:
var key = e.keyCode;
Also, why is half of it e
and later on you have event
?
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
This might also be useful for JS reference:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
You might also want to use jQuery's which
. It should work across browsers.
Upvotes: 0