只允许一个“.” 在 KeyPress 期间在 Javascript 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14574395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:00:05  来源:igfitidea点击:

Allows only one "." in Javascript during KeyPress

javascriptkeypress

提问by portgas d ace

How to allow only one "." in javascriptduring Keypress?

如何只允许一个“.” 在按键期间的javascript中?

I have a code here:

我这里有一个代码:

function allowOneDot(txt) {

        if ((txt.value.split(".").length) > 1) {

          //here, It will return false; if the user type another "."

         } 
}

回答by jbabey

I will reiterate what I said in my comment before the answer:

在回答之前,我将重申我在评论中所说的话:

And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.

如果用户粘贴一堆句号怎么办?如果他们在控制台中编辑 javascript 以完全忽略此检查怎么办?确保您正确处理验证并且没有做太多的简化。

Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one .(period) in a textbox:

现在,我们将自行承担风险,以下是您不允许用户.在文本框中键入多个(句点)的方法:

document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
    // 46 is the keypress keyCode for period     
    // http://www.asquare.net/javascript/tests/KeyCode.html
    if (e.keyCode === 46 && this.value.split('.').length === 2) {
        return false;
    }
}

Working demo

工作演示

回答by Leo supports Monica Cellio

If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it. The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.

如果您真的想允许一个点,即使用户在其中粘贴文本,您也应该使用 keyup,而不是 keypress,并且您可以保留最后一个文本值,以防您需要恢复它。但缺点是输入值已经更改,您会在键入时看到它得到更正。

(function() {
    var txt = document.getElementById('txt');
    var prevValue = txt.value;

    function allowOneDot(e) {
        var dots = 0;
        var length = txt.value.length;
        var text = txt.value;
        for(var i=0; i<length; i++) {
            if(text[i]=='.') dots++;
            if(dots>1) {
                txt.value = prevValue;
                return false;
            }
        }
        prevValue = text;
        return true;
    }
    txt.onkeyup = allowOneDot;
})();