Most web developers know that to restrict only numbers to a form input, you can do something like this:
$(function() {
$("#foobar").keypress(function(e) {
if($.inArray(e.which, range(48, 57)) == -1) {
e.preventDefault();
return false;
}
});
});
function range(start, end) {
var range = [];
for(var i = start; i <= end; i++) {
range.push(i);
}
return range;
}
Unfortunately, this does not quite get the job done on an Android with the default browser. (iPhone and Other Android browsers have not been tested, so they could suffer from the same issue. Tested on an iPhone 4S, which did not have this issue.)
On an Android, let’s say you first type “f”. Nothing happens. Awesome. Wait just a minute. You then type “a”. What happens? The “f” is put into the input field! You type “c”, the “a” is put into the field. And so on. Whatever the previously-entered character is, that’s what’s put into the field.
Here’s a jsFiddle that demonstrates the issue.
The fiddle works fine on a desktop, but try it on Android (phone or emulator). I’ve tested with Android 2.3.6 and 2.2.
Anyone run into this before? Any direction would be greatly appreciated! For now, the workaround is to remove non-numeric characters immediately afterwards (in the keyup event).
Update: Here is a fiddle that shows that preventDefault() is being reached. The problem seems to be that rather than preventing, it’s simply delaying (until the next event).
A completely different approach would be using
<input type="number">and relying on the browser to provide the appropriate interface/filtering (which mobile browsers are prone to). It does not fix the code, but should circumvent the problem, which looks like a bug, to be honest.