我有一个包含多个字段的 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/