小数点校验,只允许输入数字,小时点后只有两位

输入框只能输入数字,不允许输入文字,字母,特殊字符,小数点后只允许输入两位,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    
    <style>
        .box{
            height: 400px;
            width: 500px;
            margin: 100px auto;
            padding-top: 20px;
        }
    </style>
</head>
<body>
<div class="box">
    <input type="text" id="amount"/>
</div>
<script src="jquery.min.js"></script>
<script>
    $(function(){
        $('#amount').keyup(function(event) {
            var $amountInput = $(this);
            //响应鼠标事件,允许左右方向键移动
            event = window.event || event;
            if (event.keyCode == 37 | event.keyCode == 39) {
                return;
            }
            //先把非数字的都替换掉,除了数字和.
            $amountInput.val($amountInput.val().replace(/[^d.]/g, "").
                //只允许一个小数点
                    replace(/^./g, "").replace(/.{2,}/g, ".").
                //只能输入小数点后两位
                    replace(".", "$#$").replace(/./g, "").replace("$#$", ".").replace(/^(-)*(d+).(dd).*$/, '$1$2.$3'));
        });
        $('#amount').blur(function(event) {
            var $amountInput = $(this);
            //最后一位是小数点的话,移除
            $amountInput.val(($amountInput.val().replace(/.$/g, "")));
        });
    })
    /*$("#amount").on('keyup', function (event) {
        var $amountInput = $(this);
        //响应鼠标事件,允许左右方向键移动
        event = window.event || event;
        if (event.keyCode == 37 | event.keyCode == 39) {
            return;
        }
        //先把非数字的都替换掉,除了数字和.
        $amountInput.val($amountInput.val().replace(/[^d.]/g, "").
            //只允许一个小数点
                replace(/^./g, "").replace(/.{2,}/g, ".").
            //只能输入小数点后两位
                replace(".", "$#$").replace(/./g, "").replace("$#$", ".").replace(/^(-)*(d+).(dd).*$/, '$1$2.$3'));
    });
    $("#amount").on('blur', function () {
        var $amountInput = $(this);
        //最后一位是小数点的话,移除
        $amountInput.val(($amountInput.val().replace(/.$/g, "")));
    });
*/
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/cxx328/p/6202448.html