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

如何将二维码扫描信息填充至不同<input>输入字段?

Solution to Populate Form Fields with Scanned QR Code Data

Absolutely, this is totally feasible! Let's walk through how to adapt your existing QR scanner code to parse structured data and fill it into specific form fields, plus handle submission. Here's a step-by-step implementation:


1. Ensure Your QR Code Contains Structured Data

First, make sure the QR code encodes structured data (preferably JSON)—this is the most reliable way to map values to form fields. For example, your QR code could store a string like:

{"firstName": "Alice", "lastName": "Smith", "employeeId": "EMP-789"}

If you can't use JSON, you could use a delimiter-separated format (like Alice|Smith|EMP-789), but JSON avoids parsing headaches with special characters.

2. Add Target Input Fields to Your Page

Update your HTML to include the input fields you want to populate. Let's add them inside your existing output container:

<script type="text/javascript" src="js/jsQRreader.js"></script>
<div id="loadingMessage"> Unable to access video stream (please make sure you have a webcam enabled)</div>
<canvas id="canvas" hidden></canvas>
<div id="output" hidden>
  <div id="outputMessage">No QR code detected.</div>
  <!-- Optional: Hide the original textarea once we populate fields -->
  <textarea type="text" id="outputData" name="outputData" value="" style="width: 200px;margin-left:25px;" hidden></textarea>
  
  <!-- New form fields to populate -->
  <div id="formFields" hidden>
    <div style="margin: 10px 0;">
      <label>First Name: </label>
      <input type="text" id="firstName" name="firstName" required>
    </div>
    <div style="margin: 10px 0;">
      <label>Last Name: </label>
      <input type="text" id="lastName" name="lastName" required>
    </div>
    <div style="margin: 10px 0;">
      <label>Employee ID: </label>
      <input type="text" id="employeeId" name="employeeId" required>
    </div>
  </div>
  
  <!-- Submit button wrapped in a form -->
  <form id="qrForm" style="margin-top: 15px;">
    <input type="submit" value="Submit" style="margin-bottom: 15px;">
  </form>
</div>

3. Modify the Scanner Logic to Parse and Populate Fields

Update your JavaScript tick function to parse the scanned QR data and fill the input fields. We'll add error handling to catch invalid data:

var video = document.createElement("video");
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");
var loadingMessage = document.getElementById("loadingMessage");
var outputContainer = document.getElementById("output");
var outputMessage = document.getElementById("outputMessage");
var outputData = document.getElementById("outputData");
var formFields = document.getElementById("formFields");

function drawLine(begin, end, color) {
  canvas.beginPath();
  canvas.moveTo(begin.x, begin.y);
  canvas.lineTo(end.x, end.y);
  canvas.lineWidth = 4;
  canvas.strokeStyle = color;
  canvas.stroke();
}

navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } }).then(function(stream) {
  video.srcObject = stream;
  video.setAttribute("playsinline", true);
  video.play();
  requestAnimationFrame(tick);
});

function tick() {
  loadingMessage.innerText = "Loading video..."
  if (video.readyState === video.HAVE_ENOUGH_DATA) {
    loadingMessage.hidden = true;
    canvasElement.hidden = false;
    outputContainer.hidden = false;

    canvasElement.height = video.videoHeight;
    canvasElement.width = video.videoWidth;
    canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);

    var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
    var code = jsQR(imageData.data, imageData.width, imageData.height, {
      inversionAttempts: "dontInvert",
    });

    if (code) {
      // Keep your existing QR border drawing code
      drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
      drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
      drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58");
      drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58");
      
      outputMessage.hidden = true;
      outputData.value = code.data;

      try {
        // Parse JSON data from QR code
        const qrData = JSON.parse(code.data);
        
        // Populate each input field with corresponding data
        document.getElementById('firstName').value = qrData.firstName || '';
        document.getElementById('lastName').value = qrData.lastName || '';
        document.getElementById('employeeId').value = qrData.employeeId || '';
        
        // Show the form fields
        formFields.hidden = false;
      } catch (err) {
        // Handle invalid JSON (e.g., QR code has unstructured text)
        outputMessage.hidden = false;
        outputMessage.innerText = "QR code contains invalid structured data. Please scan a valid code.";
        formFields.hidden = true;
      }
    } else {
      // Reset state if no QR code is detected
      outputMessage.hidden = false;
      outputMessage.innerText = "No QR code detected.";
      formFields.hidden = true;
    }
  }
  requestAnimationFrame(tick);
}

// Handle form submission (AJAX example - no page refresh)
document.getElementById('qrForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  // Collect form data
  const formData = new FormData(this);
  
  // Send data to your backend (replace /save-qr-data with your endpoint)
  fetch('/save-qr-data', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    alert('Data saved successfully!');
    // Reset form after submission
    this.reset();
    formFields.hidden = true;
  })
  .catch(err => {
    console.error('Error saving data:', err);
    alert('Failed to save data. Please try again.');
  });
});

Key Notes:

  • Backend Setup: You'll need a server-side endpoint (like /save-qr-data) to receive the POST request and save the data to a database or file. The exact implementation depends on your tech stack (Node.js, PHP, Python, etc.).
  • Alternative Data Formats: If you can't use JSON, adjust the parsing logic. For example, if your QR code uses pipe-separated values (Alice|Smith|EMP-789), replace the JSON parse step with:
    const qrData = code.data.split('|');
    document.getElementById('firstName').value = qrData[0] || '';
    document.getElementById('lastName').value = qrData[1] || '';
    document.getElementById('employeeId').value = qrData[2] || '';
    
  • Validation: Add frontend validation (like the required attribute on inputs) to ensure all fields are filled before submission.

内容的提问来源于stack exchange,提问作者A.Zaimaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:43:52