过滤字母,只能输入数字的设置

<form method="get">
    <textarea  rows="10" cols="30" style="ime-mode:disabled"></textarea>   
    <!--style="ime-mode:disabled"禁止输入法(谷歌不支持)-->
</form>
<script>
    window.onload=function(){
        var fm=document.forms[0];
        var text=fm.elements[0];
        text.onkeypress=function(evt){       //用keydown不能获取小键盘上数字
        var code=getCharcode(evt);
        txt=String.fromCharCode(code);
        if(!/\d/g.test(txt) && code>8){  //code>8 避免delete键,光标,backspace键被屏蔽
            alert("只能输入数字")
            getdefalut(evt)
                    }
                }
            //获取键盘字母或数字编码
            function getCharcode(e){
                var e=e||window.event;
                return e.charCode || e.keyCode    //IE中需要用keycode返回触发键值的代码
            }
            //阻止默认行为
            function getdefalut(e){
                var e=e||window.event;
                if(e.preventDefault){
                    e.preventDefault();
                }else if(e.returnVlaue){
                    e.returnVlaue=false;
                }
            }
        }
</script>

猜你喜欢

转载自blog.csdn.net/qq_33325959/article/details/78683555