js只能輸入數(shù)字

字號:


    javascript通過正則替換來實(shí)現(xiàn)text文本框只能輸入數(shù)字或者小數(shù),不能輸入漢字以及錯(cuò)誤的數(shù)字類型,原載于sosuo8,本站做部分修改.
    <html>
    <head>
    <meta http-equiv="content-Type" content="text/html;charset=gb2312">
    <title>js 只能輸入數(shù)字和小數(shù)點(diǎn)</title>
    <script language="JavaScript" type="text/javascript">
    function forasp_cn(obj)
    {
    //先把非數(shù)字的都替換掉,除了數(shù)字和.\d表示數(shù)字 \.表示點(diǎn) 而正則中的.表示出了回車和換行以外的字符.在這里正則將非數(shù)字和點(diǎn)的字符轉(zhuǎn)為空
    obj.value = obj.value.replace(/[^\d\.]/g,"");
    //必須保證第一個(gè)為數(shù)字而不是.將
    obj.value = obj.value.replace(/^\./g,"");
    //去除所有的漢字
    obj.value = obj.value.replace(/[^\x00-\xff]*/g,"");
    //保證.只出現(xiàn)一次,而不能出現(xiàn)兩次以上
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");//原文是網(wǎng)站制作學(xué)習(xí)網(wǎng)的FoAsP.cn
    }
    </script>
    </head>
    <body>
    只能輸入數(shù)字和小數(shù)點(diǎn)的文本框:<input id="input1" onblur="forasp_cn(this)" onkeyup="forasp_cn(this)">
    </body>
    </html>
    原文地址:http://www.sosuo8.com/article/show.asp?id=1420
    本站對javascript只能輸入數(shù)字做了部分修改,添加了中文的驗(yàn)證