简体   繁体   English

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

[英]Javascript/Jquery to restrict input field to one decimal and numbers only

Below is what i have so far, the problem is it works for input and for paste but if you paste again it looks like its only working for the data copied from the paste action only, its not taking into account what is already in that field. 下面是我到目前为止的问题,问题是它适用于输入和粘贴,但是如果再次粘贴,它似乎仅适用于从粘贴操作复制的数据,它没有考虑该字段中已有的内容。

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

I probably posted this question too soon without spending enough time debugging. 我可能在没有花费足够时间进行调试的情况下过早发布了此问题。 Just thought id share my solution. 只是以为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++;
        }
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM