【发布时间】:2013-08-09 06:06:10
【问题描述】:
有这样的功能,文本框只接受来自条形码扫描仪的输入,并限制来自键盘的任何其他输入。
【问题讨论】:
-
尽量阻止按键事件的默认动作
-
@Harsha,抱歉误导。这是我的问题。我将如何实现 tis 功能?
标签: javascript jquery
有这样的功能,文本框只接受来自条形码扫描仪的输入,并限制来自键盘的任何其他输入。
【问题讨论】:
标签: javascript jquery
【讨论】:
查看http://www.deadosaurus.com/detect-a-usb-barcode-scanner-with-javascript
从链接中,我已经修改为在不满足 10 个字符长度标准时自动清除文本,这可以假设不满足 10 个字符长度标准 = 不是从条形码扫描仪输入的。
我使用的是 ASP.NET,下面是我的示例:
对于 ASP 代码:
<asp:TextBox ID="TextBoxComponentPartNumber" runat="server" onkeypress="AutoClearOrSetInputText(event,this.id);" ></asp:TextBox>
<asp:TextBox ID="TextBoxAssemblyPartNumber" runat="server" onkeypress="AutoClearOrSetInputText(event,this.id);" ></asp:TextBox>
对于 JavaScript:
<script type="text/javascript">
//This variables is for AutoClearOrSetInputText function
var pressed = false;
var chars = [];
//This function will auto clear or set input text box’s text value
function AutoClearOrSetInputText(eventForTextBox,idForTextBox) {
// add each entered char to the chars array
chars.push(String.fromCharCode(eventForTextBox.which));
// variable to ensure we wait to check the input we are receiving
if (pressed == false) {
// we set a timeout function that expires after 0.5 sec, once it does it clears out a list
// of characters
setTimeout(function() {
// check we have a long length e.g. it is a barcode
if (chars.length >= 10) {
// join the chars array to make a string of the barcode scanned
var barcode = chars.join(“”);
// assign value to input for barcode scanner scanned value
document.getElementById(idForTextBox).value = barcode;
}
else {
// clear value from input for non-barcode scanner scanned value
document.getElementById(idForTextBox).value = ”;
}
chars = [];
pressed = false;
}, 500);
}
// set press to true so we do not reenter the timeout function above
pressed = true;
}
</script>
【讨论】: