input type=number 中可以随意输入任意字符,但是如果该字符不是纯数字(负数,小数也行),对应dom元素的value就是空(""),这样我就无法区分用户到底是输入了一些非法的字符如(20A)还是把input清空了,有参数配置或者折中的解决方案吗?
http://jsfiddle.net/rd408710/
JavaScript 有个 API 可以先验证有效性:
window.c = function(e){
if(e.currentTarget.validity.valid) {
console.log(e.currentTarget.value);
}
}
如果输入不合法,valid
返回 false
。如果用户清空了 <input>
,valid
是 true
。
好像没啥办法,要么监听keypress
阻止非数字的输入防止一种情况的出现,具体请参考:http://stackoverflow.com/questions/15627341/get-value-of-input-type-number-with-js-when-it-contains-non-numeric-characte
要么就是换成type="tel"
,具体请参考:http://stackoverflow.com/questions/18677323/html5-input-type-number-value-is-empty-in-webkit-if-has-spaces-or-non-numeric-ch?rq=1