JavaScript限制输入框只允许输入数字和小数点后两位
<p><input type='text' oninput='handleInput(this)' />/n/n<script>/nfunction handleInput(input) {/n // 获取输入的内容/n let value = input.value;/n/n // 替换非数字字符为 ''/n value = value.replace(/[^/d.]/g, '');/n/n // 只保留小数点后两位/n const index = value.indexOf('.');/n if (index !== -1) {/n value = value.slice(0, index + 3);/n }/n/n // 更新输入框的值/n input.value = value;/n}/n</script>/n/n这段代码实现了一个输入框,只允许输入数字和小数点,并且限制小数点后最多保留两位。具体实现步骤如下:/n/n1. <strong>监听输入框的 <code>oninput</code> 事件:</strong> 当输入框的内容发生变化时,会触发 <code>oninput</code> 事件,并调用 <code>handleInput</code> 函数。/n2. <strong>获取输入内容:</strong> <code>handleInput</code> 函数首先获取输入框中的内容。/n3. <strong>使用正则表达式替换非数字字符:</strong> 使用 <code>replace(/[^/d.]/g, '')</code> 将输入内容中的非数字字符替换为空字符串。/n4. <strong>限制小数点后两位:</strong> 如果输入内容包含小数点,使用 <code>indexOf('.')</code> 找到小数点的索引,然后使用 <code>slice(0, index + 3)</code> 只保留小数点后两位。/n5. <strong>更新输入框的值:</strong> 最后将处理后的内容更新到输入框中。/n/n通过以上步骤,可以确保输入框中只包含数字和小数点,并且小数点后最多只有两位。</p>
原文地址: https://www.cveoy.top/t/topic/mwdd 著作权归作者所有。请勿转载和采集!