This jsfiddle demonstrates the following issue.
The simplest example is:
console.log(document
You're not supposed to use <input type=number>
for things that are not numbers (in very mathematical sense—it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
You can test whether device supports type=number
and attach your fallback only if it doesn't:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.
This is what I was looking for:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to @int32_t for the suggestion.