3 回答

TA贡献1111条经验 获得超0个赞
好像你在听按键。使用计时器取消它。去抖动方法的基本思想。
var timer;
function autofill(value){
if (timer) window.clearTimeout(timer);
if(value.length === 9){
timer = window.setTimeout( function () {
processIt(value);
}, 50);
} else if(value.length === 12){
processIt(value);
}
}
function processIt(value){
console.log('here', value);
}
但这是一个糟糕的解决方案。通常,您将扫描仪设置为触发标签或输入 press,这样您就知道它已完成。我会检查是否发生这种情况,然后改为倾听。然后你可以只听那个,你就知道扫描仪已经完成了。
var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
if (["Tab", "Enter"].includes(evt.key)) {
evt.preventDefault();
console.log('scanner is done', evt.target.value);
}
});
<input type="text" id="barcode" />

TA贡献1810条经验 获得超5个赞
对于最常见的场景,扫描仪会一个一个触发这样的事件:焦点,输入字符....输入最后的'Enter'字符,所以你必须关注最后一个事件。
<script type="text/javascript">
window.addEventListener("load", function () {
var ic = document.getElementById("IC-input");
ic.addEventListener("focus", function (args) {
ic.value = "";
});
ic.addEventListener("keyup", function (args) {
if (args.key == "Enter") {
autofill(ic.value);
}
});
});
function autofill(value) {
console.log("Autofill:" + value)
//console.log(9 digits);
button = document.getElementById("theButton");
if (value.length == 9) {
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
</script>
<span>
<input type="text" id="IC-input" name="IC" onkeyup="input_keyup" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>

TA贡献1828条经验 获得超6个赞
问题是一旦输入框有 9 个字符,自动填充功能就会运行以按下按钮。这是因为您正在通过附加到输入标签的“onkeyup”事件侦听器运行自动填充功能。
解决方案是在确保有预期的全长值后运行自动填充功能。祝你好运。
添加回答
举报