Javascript:隐藏输入条码扫描器

问题描述

这是我当前的设置: 我有一个键盘模式下的条形码扫描仪。 我试图扫描到一个隐藏的、失焦的输入。 我试图读取的条形码如下:asterisk[barcode-info]asterisk 并粘贴为 |[barcode-info]。 (Stackoverflow 不允许我只放置星号,但这就是 asterisk 代表的含义。)

<form method="post">
  <input type="hidden" name="action" value="barcode-scan"/>
  <input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>

我一直无法弄清楚如何进行,但是当输入条码时,我希望 Javascript 捕获它并更新“条码输入”隐藏输入,然后将其提交给服务器。我已经弄清楚了服务器端,只是不知道如何从 JS(不是 Jquery)获取隐藏的输入。

有人建议尝试使用粘贴事件侦听器,但它似乎根本没有捕获输入。扫描仪可以工作,因为我可以在焦点对准时输入 type="text"。

更新:由于下面的精彩建议,我已经能够使输入正常工作!该表单将测试两个特定的输入是否相互跟随,然后它将执行下一个函数。否则,它将删除日志常量中包含的任何信息。最终,是的,我让它正常工作了!

document.addEventListener('keyup',function(e){
        const log = document.getElementById('barcode-input');
        log.textContent += ' ' + e.code;
        document.getElementById('barcode-input').value = log.textContent;

        if (log.textContent.startsWith(' ShiftLeft')) {

            if (log.textContent.startsWith(' ShiftLeft Backslash')) {
            document.getElementById('barcode-input').form.submit();
            console.log('e.code,submit barcode info');
            }
        }

        else {
            log.textContent = '';
            document.getElementById('barcode-input').value = '';
        }
    });

解决方法

如果屏幕上没有 input[type="text"] 元素,您将需要手动捕获键盘输入。类似的东西:

document.addEventListener('keydown',(ev) => {
  if (ev.ctrlKey || ev.altKey) return;  // Ignore command-like keys
  if (ev.key == 'Enter') {
    // ...submit the content here...
  } else if (ev.key == 'Space') { // I think IE needs this
    document.getElementById('barcode-input').value += ' ';
  } else if (ev.key.length == 1) { // A character not a key like F12 or Backspace
    document.getElementById('barcode-input').value += ev.key;
  }
});

这应该能让你大获全胜......

,

或者,不是在输入或输入值 (*'s) 上查找事件,而是在值上定义事件并使用输入事件来简单地设置值。

一旦输入停止,无论是 1 秒(或者很可能更短),然后关闭表单。

如果您必须将光标置于输入中,请扫描。您唯一的选择是使用 autofocus 属性并隐藏输入,因为您无法聚焦隐藏元素,尽管您也无法聚焦多个,因此请记住,如果您要扫描多个输入,则必须显示输入,无法绕过它。

例如

SELECT case when len(a.Code) = 6 then
        case 
            when substring(a.code,1,1) LIKE '%[a-z]%' 
                and substring(a.code,2,1) like substring(Code,PatIndex('%[0-9.-]%',Code),1)
                and substring(a.code,3,1) = ' '
                and substring(a.code,4,1)
             then 1 
        end
      end as mapping,code
let elm = document.querySelector('input[name="barcode-input"]')

// watcher on the value,after 1 second,it invokes an event,i.e post form
let timer = 0
Object.defineProperty(window,'barcode',{
  get: function () { return this.value },set: function (value) {
    clearTimeout(timer)
    this.value = value
    timer = setTimeout(() => {
      console.log('Post form')
    },1000) // do some tests,tweak if much less then 1 second to input the value 
  }
})

// it should trigger input even if its a keyboard
elm.addEventListener("input",e => barcode = e.target.value)

// ignore,below this line..

// set a value of barcode at intervals,only when its stopped entering (>1 second),then will it fire the callback
let i = 0
let t = setInterval(() => {
  barcode = (barcode || '')+"X"
  if (i >= 40) clearInterval(t)
  i++
},100)

// ignore... grab value from hidden input,put in #current
setInterval(() => document.querySelector('#current').innerHTML = barcode,1000)

,

这是使用 keypress 扫描传入密钥流的 *[ 并捕获条形码直到它看到 ]* 的演示程序。然后它将代码发送到服务器。尽管我在您的 HTML 中复制了该表单,但此处的代码并未使用它。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Working...
<form method="post">
    <input type="hidden" name="action" value="barcode-scan"/>
    <input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>
<p id="response"></p>
<script>
    (function(){
        "use strict";
        const bcAst = '*';
        const bcLeft = '[' ;
        const bcRight = ']';

        let barcodeIncoming = false;
        let lastChar = 0;
        let barcode = '';

        document.addEventListener('keypress',function(e){

            function sendCode(barcode) {
                console.log(barcode);
                let fd = new FormData();
                fd.append('barcode',barcode);
                fetch('myFile.php',{
                    method: 'POST',body: fd
                })
                .then(resp=>{
                    resp.text().then(txt=>{document.getElementById('response').innerText = txt;})
                });
            }

            console.log(e.key);
            switch (e.key) {
                case bcAst:
                    if (barcodeIncoming && (lastChar === bcRight)) {
                        barcodeIncoming = false;
                        sendCode(barcode);
                    }
                    break;
                case (bcLeft):
                    if (lastChar === bcAst) {
                        barcodeIncoming = true;
                        barcode = '';
                    }
                    break;
                case (bcRight):
                    break;
                default:
                    barcode += (barcodeIncoming)?e.key:'';
                    break;

            }
            lastChar = e.key;

        });
    })();
</script>
</body>
</html>

当前的服务器文件非常简陋,但在这里可以起到作用:

<?php
if (isset($_POST['barcode'])) {
    echo "Your barcode is {$_POST['barcode']}";
} else {
    echo "No barcode found";
}

注意 - 这仅进行了基本测试。您将希望提高其在与密钥流中的类似数据可能发生冲突时的恢复能力。

,

转自

<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />

<input type="test" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" style="display:none;" />