JS实现Input框限制正数(保留三位有效数字,并且有最大值100限制)

                <div class="form-group row">
                    <label class="col-form-label col-md-3 label_required">Tax Rate:</label>
                    <div class="col-md-4 col-lg-8" style="position:relative">
                        <input id="NewTaxRate" class="form-control" formcontrolname="rate" type="text">
                        <span style="padding-top: 7px; font-weight: bold; position: absolute; right: 48px; top: 2px;">
                            %
                        </span>
                    </div>
                </div>

JS代码:

    $(function () {
        $("#NewTaxRate").on('input',
            function (e) {
                var str = $(this).val();
                str = str.replace(/[^\d.]/g, '');

                if (str !== "") {
                    var index1 = str.indexOf('.');

                    if (str.indexOf('.') !== -1) { //带小数点
                        var beforePoint = str.substring(0, index1);

                        var afterPoint = str.substring(index1 + 1);
                        afterPoint = afterPoint.replace('.', '');

                        if (afterPoint.length > 3) {
                            afterPoint = afterPoint.substring(0, 3);
                        }

                        var lastStr = beforePoint + "." + afterPoint;
                        $(this).val(lastStr);
                    } else { //不带小数点
                        var arr = str.split('.');
                        var res = arr.join("").replace(/^0*/g, '');

                        if (res > 100) {
                            res = "100";
                        }
                        $(this).val(res);
                    }
                } else {
                    $(this).val("");
                }
            });
    });
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值