限制文本框只输出数字

方法一:

<input type="text" class="inputface" name="qczs" maxlength="2" style="width:25px;" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" />

<input type="text"
onkeypress = 'return /^\d$/.test(String.fromCharCode(event.keyCode))'
oninput= 'this.value = this.value.replace(/\D+/g, "")'
onpropertychange='if(!/\D+/.test(this.value)){return;};this.value=this.value.replace(/\D+/g, "")'
onblur = 'this.value = this.value.replace(/\D+/g, "")'/>

上面四事件组合,兼容Firefox、IE、Chrome。

 

JS实现
<script type="text/javascript">
function getEvent() {
    if (document.all) {
        return window.event; //for ie
    }
    func = getEvent.caller;
    while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0) {
            if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                return arg0;
            }
        }
        func = func.caller;
    }
    return null;
}
function doit(){
    var ev = getEvent();
    if(ev.keyCode < 48 || ev.keyCode > 57) return false;
}
</script>
<input type="text" id="txt" onkeydown="return doit()">

 

posted @ 2016-01-26 13:56  suzmin  阅读(181)  评论(0编辑  收藏  举报