我想强制我的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/