Reputation: 44715
I have a number input, which I want user to by unable to insert any non-digit characters. We have attempted this in a number of ways:
We started with removing all non-numeric characters on blur:
$(my_input).blur(function() {
$(this).val($(this).val().replace(/[^\d]/, '')
}
The problem with the code above is that number field's val
function returns empty string if the input is invalid. We definitively want a number field as our website is to be used on mobiles.
The option which I would prefer is to use keydown
event:
$(my_input).keydown(function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
});
The above works almost as a charm. The problems are:
numeric keyboard not included in a range - this can be however easily fixed and is not a subject of this question.
For unknown to me reasons js on iOS is using different key codes, hence this is not working on huge part of mobile phones, iPads etc.. This is a deal breaker.
So the question - is there any way to determine which key was actually pressed with an keydown
event. I have seen number of similar questions, none of them however covered those iOS differences. I've noticed that event has a 'key' property, however I am not sure how reliable this property is.
Upvotes: 1
Views: 146
Reputation: 1118
You can try it this way
sample text box
<input type="text" name="sample" id="sample" onkeyup="positiveNumericOnly(this);" />
JS Code
function positiveNumericOnly(ele)
{
tempVal = ele.value.replace(/[^\d]/g, "");
if(tempVal != ele.value)
ele.value = tempVal;
}
Upvotes: 0
Reputation: 1789
EDIT: I fell on this post which might be a neat way to solve your problem: JavaScript: Avoiding hardcoded keycodes
It would boil down to
var digitCodes = "0123456789".split('').map(function (x) { return x.charCodeAt(0); });
There might be a better way to do this but you could detect if the device is running iOS (c.f. Detect if device is iOS) and use the appropriate keycodes (c.f. http://notes.ericjiang.com/posts/333).
var digitCodes;
if (isiOS()) {
digitCodes = keycodes.ios;
}
else {
digitCodes = keycodes.default;
}
if (digitCodes.indexof(e.which) != -1) {
...
}
Something like that...
Upvotes: 1