gpt4 book ai didi

javascript - KeyPress 期间 Javascript 中仅允许一个 "."

转载 作者:行者123 更新时间:2023-11-28 12:02:14 29 4
gpt4 key购买 nike

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

我这里有一个代码:

function allowOneDot(txt) {

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

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

}
}

最佳答案

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

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.

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

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

关于javascript - KeyPress 期间 Javascript 中仅允许一个 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574395/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com