js控制文本框只能输入数字

来源:岁月联盟 编辑:exp 时间:2012-09-14

js代码:

[javascript] 
<script type="text/javascript"> 
        function NumOnly(e) { 
            var key; 
            if (window.event) { 
                key = event.keyCode; 
            } 
            else { 
                key = e.which; 
            } 
            if (key > 47 && key < 58 || key == 8 || key == 45) { 
                return; 
            } 
            else if (window.event) { 
                window.event.returnValue = null; 
            } 
            else { 
                if (e && e.preventDefault) 
                    e.preventDefault(); 
            } 
        } 
    </script> 


文本框代码:
[csharp]
<asp:TextBox ID="txtPhone" Width="234px" onkeypress="NumOnly(this)" MaxLength="11" 
                                            runat="server"></asp:TextBox>