javascript-限制文本框只输入数字

使用onInput()事件

oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有用,在内容修改后立即被触发,不像 onchange 事件需要失去焦点才触发。oninput 事件在主流浏览器的兼容情况如下:

 

 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>RunJS</title>
    </head>
    <body>
        <input type="text" onInput ="keypress(this)" />
    </body>
    </body>
</html>

// scripts
function keypress(_this){
    _this.value = _this.value.replace(/[^0-9]/g, '');
}
posted @ 2017-08-02 14:34  GordonDicaprio  阅读(361)  评论(0编辑  收藏  举报