【问题标题】:allow textbox input from barcode scanner only and restrict any input from keyboard仅允许从条形码扫描仪输入文本框并限制从键盘输入
【发布时间】:2013-08-09 06:06:10
【问题描述】:

有这样的功能,文本框只接受来自条形码扫描仪的输入,并限制来自键盘的任何其他输入。

【问题讨论】:

  • 尽量阻止按键事件的默认动作
  • @Harsha,抱歉误导。这是我的问题。我将如何实现 tis 功能?

标签: javascript jquery


【解决方案1】:

以下是用于限制键盘输入..只需尝试连接您的条形码扫描仪并检查它是否有效..

 textBox.onkeypress = function(e) {
       e = e || window.event;
       var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
       if (/\D/.test(String.fromCharCode(charCode))) {
           return false;
       }
    };

LIVE DEMO

对于字母数字

看看这个

LIVE DEMO

【讨论】:

  • 我希望它接受字母数字?我应该说:e.which == "alphanumeric" ??
  • 谢谢,我稍后再试试 .. 我们的条形码扫描仪现在不可用 :)
  • 我仍然可以使用键盘。这是为什么?
  • 仍然可以从键盘输入。
【解决方案2】:

查看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> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2023-03-17
    • 2016-12-21
    • 2011-07-12
    相关资源
    最近更新 更多