问题
This jsfiddle demonstrates the following issue.
The simplest example is:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
It appears jQuery's .val() method gives the same result.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/15627341/get-value-of-input-type-number-with-js-when-it-contains-non-numeric-characte