You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于jQuery实现意大利电子发票二维码扫描及表单自动填充

Solution for Parsing Italian Electronic Invoice QR Code Data with jQuery

Great question! Since barcode scanners act like virtual keyboards, the key is to distinguish their fast, continuous input from manual typing and capture the JSON data without cluttering the UI. Let’s tackle each of your issues one by one:


1. jQuery Plugins for Universal Scanner Support

You don’t need heavy plugins, but a lightweight tool designed to detect scanner input (vs. manual typing) will save you a lot of hassle. The most reliable one is jquery-scannerdetection:

  • It detects scanner input by measuring character entry speed (scanners input characters in ~5-10ms intervals, while humans take 100+ms)
  • Works with nearly all USB/Bluetooth scanners that simulate keyboard input
  • Handles common scanner end markers (like a carriage return \r or newline \n)

If you prefer a no-plugin approach, you can build a custom detector (more on that below), but the plugin simplifies edge cases like varying scanner configurations.


2. How to Listen for Scanner Events

Option A: Using jquery-scannerdetection

First, include the plugin (along with jQuery) in your page. Then bind the scanner detection to your hidden input or the document:

$(document).ready(function() {
  // Initialize scanner detection
  $(document).scannerDetection({
    timeBeforeScanTest: 200, // Wait 200ms after last character to confirm scan
    endChar: [13], // Most scanners send Enter (ASCII 13) at the end
    onComplete: function(scannedData) {
      // Trigger parsing once full scan is detected
      parseScannedJSON(scannedData);
    },
    onError: function(errorMsg) {
      console.error("Scan error:", errorMsg);
    }
  });
});

Option B: Custom No-Plugin Listener

If you don’t want to use a plugin, track input timing manually to distinguish scans from typing:

$(document).ready(function() {
  let scanBuffer = "";
  let lastKeyTime = 0;
  const SCAN_THRESHOLD = 100; // Max ms between characters for a valid scan

  $(document).on("keydown", function(e) {
    const currentTime = new Date().getTime();
    const timeSinceLastKey = currentTime - lastKeyTime;

    // Reset buffer if time between keys is too long (manual typing)
    if (timeSinceLastKey > SCAN_THRESHOLD) {
      scanBuffer = "";
    }

    // Add character to buffer (skip Enter key)
    if (e.keyCode !== 13) {
      scanBuffer += String.fromCharCode(e.which);
    } else {
      // Enter key pressed: scan is complete
      parseScannedJSON(scanBuffer);
      scanBuffer = "";
    }

    lastKeyTime = currentTime;
  });
});

3. Capture Scanned Data Without Displaying It

The cleanest way is to use a visually hidden but focusable input field (avoid type="hidden"—some scanners won’t send input to hidden fields). Set it up in your HTML like this:

<!-- Hidden input to capture scan data -->
<input 
  type="text" 
  id="scan-capture" 
  style="position: absolute; left: -9999px; top: -9999px;"
  autocomplete="off"
>

<!-- Your form fields matching the JSON structure -->
<form id="invoice-form">
  <label>Country (naz):</label>
  <input type="text" id="naz"><br>

  <label>Tax Code (cf):</label>
  <input type="text" id="cf"><br>

  <label>VAT Number (piva):</label>
  <input type="text" id="piva"><br>

  <label>Company Name (denom):</label>
  <input type="text" id="denom"><br>

  <label>Province (prov):</label>
  <input type="text" id="prov"><br>

  <label>SDI PEC:</label>
  <input type="email" id="pec"><br>

  <!-- Add remaining fields for domFisc, SDI, etc. -->
</form>

Then, auto-focus the hidden input so the scanner sends data there instead of random form fields:

$(document).ready(function() {
  // Auto-focus hidden input on page load
  $("#scan-capture").focus();

  // Re-focus if user clicks elsewhere (optional but helpful)
  $(document).on("click", function() {
    $("#scan-capture").focus();
  });

  // ... scanner detection code from above ...
});

Full Parsing Function

Here’s your parsing function with error handling to avoid crashes if the QR code data is invalid:

function parseScannedJSON(scannedData) {
  try {
    const parsed = JSON.parse(scannedData);

    // Populate form fields with optional chaining to handle missing data
    $("#naz").val(parsed.anag?.naz || "");
    $("#cf").val(parsed.anag?.cf || "");
    $("#piva").val(parsed.anag?.piva || "");
    $("#denom").val(parsed.anag?.denom || "");
    $("#prov").val(parsed.anag?.domFisc?.prov || "");
    $("#cap").val(parsed.anag?.domFisc?.cap || "");
    $("#com").val(parsed.anag?.domFisc?.com || "");
    $("#ind").val(parsed.anag?.domFisc?.ind || "");
    $("#pec").val(parsed.SDI?.pec || "");
    $("#cod").val(parsed.SDI?.cod || "");
  } catch (error) {
    alert("Invalid QR code data. Please scan a valid Italian electronic invoice QR code.");
    console.error("JSON parse error:", error);
  }
}

Key Notes:

  • Most scanners let you configure the end character (usually Enter) via their software—confirm this matches your listener setup.
  • Optional chaining (?.) ensures your code doesn’t break if a field is missing from the QR code JSON.
  • Test with your specific scanner to adjust the SCAN_THRESHOLD or timeBeforeScanTest values if needed.

内容的提问来源于stack exchange,提问作者Giuseppe Lodi Rizzini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:57:30