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

标签 javascript keypress

如何只允许一个“.”在按键期间的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/

相关文章:

javascript - 使用 Qr 图像的学生考勤系统包含学生 ID

javascript - 使用 HTML/CSS 在非常规形状周围渲染框阴影

javascript - CKEditor5,如何测试简单插件的概念验证?

jquery - 强制tinymce通过回车键输入换行符而不是创建一个新段落

Python : pygame. key.get_pressed 不起作用

javascript - jQuery:防止回车键

javascript - 弹性 : Error #2048 when connecting to a WebSocket

javascript - 生成最多 50 个随机数。让用户使用 JavaScript 猜测最多 5 倍的随机数

c# - 如何将文本框插入符号向右移动

javascript - 防止按键事件中输入字段出现空格