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

hal*_*een 6 html javascript

我有几个领域的HTML.其中一个字段仅允许数字输入.但是现在我希望当用户执行时将所有字符粘贴到该字段中,除了剥离或删除的数字.

例如用户粘贴:

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

1.234.567 - > 1234567

1,234,567 - > 1234567

等等

Mih*_*rga 12

使用正则表达式.

<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>?
Run Code Online (Sandbox Code Playgroud)

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

<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>?
Run Code Online (Sandbox Code Playgroud)