文本框数字每4位自动加空格分隔

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>
            数字每4位加空格
        </title>
        <script type="text/javascript">
            window.onload = function() {
                var t = document.getElementById("test");
                t.onkeydown = change;
                t.onkeyup = change;
                t.onkeypress = change;
            }
            function change() {
                this.value = this.value.replace(/\D/g, '').replace(/....(?!$)/g, '$& '); //替换空格前4位数字为4位数字加空格
            }
        </script>
    </head>
    
    <body>
        <input type="text" id="test" />
    </body>

</html>


 

posted @ 2013-12-04 17:10  网事  阅读(479)  评论(0编辑  收藏  举报