javascript - 在粘贴事件 Javascript 中删除输入字段中的所有非数字字符

标签 javascript html

我有一个包含多个字段的 html。其中一个字段只允许输入数字。但现在我希望当用户将所有字符粘贴到该字段时,除了被剥离或删除的数字。

例如用户粘贴:

$1 234 567 -> 输入字段中的 1234567

1.234.567 -> 1234567

1,234,567 -> 1234567

等等

最佳答案

使用正则表达式。

<input id="inputBox" name="inputBox" />
<script type="text/javascript">
var inputBox = document.getElementById('inputBox');
inputBox.onchange = function(){
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
}
</script>​

或者您可以使用计时器不断检查该字段。

<input id="inputBox" name="inputBox" />
<input id="inputBox2" name="inputBox2" />
<script type="text/javascript">
var timer = new Array();
function checkFields(el){
    var inputBox = document.getElementById(el);
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
    clearTimeout(timer[el]);
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
function timerFields(el){
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
timerFields('inputBox');
timerFields('inputBox2');
</script>​

关于javascript - 在粘贴事件 Javascript 中删除输入字段中的所有非数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12050403/

相关文章:

javascript - 如何使用 react-router-dom 防止浏览器返回并保持状态

html - 报表查看器中的重叠表格

HTML 定位更多元素

javascript - 如果打开导航栏,则添加过渡到背景颜色更改

javascript - 如何使标题居中?

javascript - 另一个D3向强制有向图添加文本

javascript - 为什么我不通过 javascript 从 Object.key 获取值

javascript - 对象 JavaScript,无法读取未定义的属性...之前已读取

html - 悬停时的相对背景颜色

javascript - Karma 错误 - 没有捕获浏览器,打开 http ://localhost:9876/