javascript - 使用InputMask html(jqueryl或js)强制html输入中的小数?

标签 javascript jquery html regex

我想强制我的html输入显示以下内容:最大14个尾数(从1到14)和有效的三位小数点,如果用户在采用默认000后没有指定点的值 示例:输入 5 显示 5.000 输入 5.2 显示 5.200 输入22222显示22222.000显示。 请帮忙

最佳答案

使用.indexOf检查.字符。确保它存在并检查其索引后面的子字符串的长度。如果小于 3,请添加一些零。

HTML

<input type="text" id="input" maxlength="14" value="" />

JavaScript

/* Select the desired input, and add an onChange event listener */
document.querySelector('#input').onchange = function () {
    /* if the user didn't add a dot, we add one with 3 zeros */
    if (this.value.indexOf('.') == -1) this.value += '.000';

    /* Otherwise, we check how many numbers there are after the dot
       and make sure there's at least 3*/
    if (this.value.substring(this.value.indexOf('.') + 1).length < 3)
        while (this.value.substring(this.value.indexOf('.') + 1).length < 3)
            this.value += '0';
};

Live Demo

关于javascript - 使用InputMask html(jqueryl或js)强制html输入中的小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273209/

相关文章:

javascript - 为什么无法将信息从 html li 标签传输到 jQuery 函数?

Java Servlet 继续发送消息

javascript - 隐藏或禁用 DevExtreme Scheduler 中的编辑属性以及其他问题?

javascript - Google Analytics - 如何在提交表单时跟踪登录用户的 ID

javascript - 如果条件不起作用,则在 td 上应用不同颜色的颜色

javascript - jquery .on 根据所选值更改输入字段中的实时更新

javascript - 在 Chrome 扩展中获取 GMail 的 "To"字段

javascript - 使用jquery显示值

javascript - 在 anchor 标记顶部显示交互式 Html 元素

javascript - jquery e.preventDefault 停止循环