使用jQuery检测扫描仪输入 [英] Detect scanner input using jquery

查看:339
本文介绍了使用jQuery检测扫描仪输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个文本框:

<input type="text"id="resourceName" placeholder="Resource name"/>
<input type="text" id="barCode"  placeholder="barCode(EAN-13)"/>

要填充此文本框,请使用条形码扫描仪和键盘. 我想要的是有点困难,我不知道该怎么做. 当用户使用键盘填充文本框和使用条形码填充文本框时,我无法区分. 我需要这个,因为我想实现以下内容:当用户使用条形码扫描器,并且如果我们没有聚焦文本框时,我想聚焦条形码文本框并将此值插入此文本框中,而当聚焦焦点是resourceName文本框时,首先要聚焦条形码文本框,然后将此值插入此文本框. 我不想让用户使用条形码扫描仪将条形码插入resourceName文本框中. 问题是我无法区分事件,用户如何使用条形码扫描仪或键盘来填充textboxex?. 任何帮助将不胜感激.非常感谢

To populate this textboxes I use barcode scanner and keyboard. What I want is a little bit difficult and I don't know how to do this . I can't differentiate when user is populating text boxes with keyboard and when with barcode. I need this becouse i want to implement something like : when user is usign barcode scanner and if we don't have focused textbox ,I want to focus barcode textbox and insert this value in this textbox , and when focused is resourceName textbox , first I want to focus barCode textbox and then to insert this value to this textbox. I don't want to let user insert barcode in resourceName textbox using barcode scanner . The problem is that i can't differentiate events , how user is populating textboxex ?, using barcode scanner or using keyboard. Any help will be appreciated.Thanks a lot

推荐答案

脱离我在评论中建议的想法,我想到了这个...

Going off the idea I suggested in the comments, I came up with this...

var _keybuffer = "";

$(document).on("keyup", function(e) {
    var code = e.keyCode || e.which;
    _keybuffer += String.fromCharCode(code).trim();
    // trim to last 13 characters
    _keybuffer = _keybuffer.substr(-13);

    if (_keybuffer.length == 13) {
        if (!isNaN(parseInt(_keybuffer))) {
            barcodeEntered(_keybuffer);
            _keybuffer = "";
        }
    }
});

function barcodeEntered(value) {
    alert("You entered a barcode : " + value);
}

它将保留最后13个按键的缓冲,如果只是数字,则假定它是条形码并触发barcodeEntered功能.显然,这是一种黑客行为,并假定没有任何人会在页面的其他位置键入13位数字(但如果某些字段具有焦点等,则可以使它忽略按键).

It keeps a buffer of the last 13 keys pressed and if it's just numbers then it assumes it's a barcode and triggers the barcodeEntered function. This is obviously a hack and assumes that there is no reason anyone would ever type a 13 figure number elsewhere on the page (but you could make it ignore key presses if certain fields had focus etc..)

它可以捕获页面上的所有按键,而与焦点无关,因此即使没有焦点,它也应捕获扫描的条形码.

It captures all key presses on the page, regardless of focus so it should capture you scanning a barcode even when nothing has focus.

编辑:根据@DenisBorisov的建议,我已经在键盘缓冲中添加了.trim()以便忽略空格.

I've added .trim() to the keyboard buffering so that spaces are ignored, as per suggestion from @DenisBorisov.

这篇关于使用jQuery检测扫描仪输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆