Javascript / Jquery将输入字段限制为一个小数和仅限数字

时间:2017-10-30 16:41:01

标签: javascript jquery html validation input

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

    $('#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++;
    })

1 个答案:

答案 0 :(得分:0)

我可能很快就发布了这个问题而没有花足够的时间调试。只是想id分享我的解决方案。

    $('#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++;
        }
    })