input type=number 中可以随意输入任意字符,但是如果该字符不是纯数字(负数,小数也行),对应dom元素的value就是空(""),这样我就无法区分用户到底是输入了一些非法的字符如(20A)还是把input清空了,有参数配置或者折中的解决方案吗?
http://jsfiddle.net/rd408710/
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
JavaScript 有个 API 可以先验证有效性:
如果输入不合法,
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