$('input').on('keyup',function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
来自:https://stackoverflow.com/a/891816/622813
我使用<input type="number">
当我输入类似1234a
的内容时,值空白
但是,当我输入<input type="text">
值1234a
1234
没有<input type="tel">
想知道为什么?
演示: http://jsfiddle.net/PV2fQ/
更新:
{{1}}这项工作很好...... http://jsfiddle.net/PV2fQ/10/ 为什么?
答案 0 :(得分:1)
如果您在替换语句之前执行了console.log(this.value);
,则会看到对于非数字输入<input type="number">
本身会获得一个空白值,即this.value = ''
;
这似乎是此输入类型的内部实现。
另一种选择:http://jsfiddle.net/PV2fQ/12/
$('input').keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});