I believe this is an easy one, but I couldn't find any answer after a couple of hours searching on google (maybe I wasn't able to use the correct words in the search :-P)
I have a javascript method that prevents the user to fill the textbox with other characters than numbers, as it can be seen in the code below, and it's used in KeyDown event:
function checkNumberInput(e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === 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();
}
}
The problem is that, if the user types accent characters that "waits" a second key (such as ~´`^), it appears in the textbox when a number is typed right after.
For example:
a) types 1 => [1________]
b) types ~ => [1________]
c) types 3 => [1~3______]
How can I prevent this from happening? Thanks in advance.
Do you mean that '
and a
are converted to а́
? This is built in the system, you cannot change that.
What you can do is check the input after that. This way you'll also prevent paste with mouse:
$('input').on('keydown', checkNumberInput).on('blur focus', function(){
var val = $('input').val();
// now remove everything that is not allowed
val = val.replace(/[^0-9.]+/g, '');
$('input').val(val);
})
(The exact implementation is deffinitely not perfect, just to illustrate what's going on)
https://jsfiddle.net/5afwdhzx/
About really instant fix - give this closure a name and call it inside the keyDown function with some short delay, like @haroldo said above.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments