【问题标题】:Javascript/Jquery to restrict input field to one decimal and numbers onlyJavascript/Jquery 将输入字段限制为一位小数和数字
【发布时间】:2023-05-04 19:20:02
【问题描述】:

下面是我到目前为止的内容,问题是它适用于输入和粘贴,但如果你再次粘贴,它看起来只适用于从粘贴操作复制的数据,它没有考虑到已经存在的内容在那个领域。

    $('#val00').on('input', function(){
        this.value = this.value
        .replace(/[^\d.]/g, '')             // numbers and decimals only
        .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
        .replace(/(\.[\d]{2})./g, '$1');    // not more than 2 digits after decimal
        console.log("ON INPUT "+mynum);
        mynum++;
    })

    $('#val00').on('paste', function(){
        this.value = this.value
        .replace(/[^\d.]/g, '')             // numbers and decimals only
        .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
        .replace(/(\.[\d]{2})./g, '$1');    // not more than 2 digits after decimal
        console.log("ON PASTE "+mynum);
        mynum++;
    })

【问题讨论】:

    标签: javascript jquery html validation input


    【解决方案1】:

    我可能过早地发布了这个问题,而没有花足够的时间进行调试。只是想我分享我的解决方案。

        $('#val00').on('paste', function(){
    
            if (this.value !="") {
                this.value = ""
            }else{
            this.value = this.value
            .replace(/[^\d.]/g, '')             // numbers and decimals only
            .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
            .replace(/(\.[\d]{2})./g, '$1');    // not more than 2 digits after decimal
            console.log("ON INPUT "+mynum);
            mynum++;
            }
        })
    

    【讨论】:

    • 当我在测试时,这似乎根本不起作用——我似乎能够不受阻碍地将任何我喜欢的东西粘贴到输入字段中。 jsfiddle
    最近更新 更多