Search code examples
javascriptjquery

Scan QR Code value into an input field after successful scan


This is the scanner I am using...

https://github.com/takanori-matsushita/webcodecamjs

It's working 100%. But I need to add some custom extra's.

When the QR Code is scanned it outputs my result into this paragraph tag.

<p id="scanned-QR"> The scanned code text value is printed out here </p>

However I need it to be an input field so I can use it's value in a url.

How can I set an input field equal to the value submitted to the Paragraph tag?

I have tried these methods and they failed :

Method 1

<input id="scanned-QR"> The scanned code text value is printed out here </input>

Method 2

<p id="scanned-QR" onchange="update"></p>
 <input id="code_id_value" type="text" name="" value="">
<br>

<script>
 function update(){
  var code_id_value = document.getElementById("scanned-QR").innertext;
  document.getElementById("code_id_value").value = code_id_value;
 }
</script>

Solution

  • The key that you're missing is that the T in .innertext needs to be capitalised (as .innerText).

    In addition to this, using inline event handlers is bad practice, and you should consider using .addEventListener() instead of onchange.

    This can be seen working in the following:

    document.getElementById("scanned-QR").addEventListener("click", update);
    
    function update() {
      var code_id_value = document.getElementById("scanned-QR").innerText;
      document.getElementById("code_id_value").value = code_id_value;
    }
    
    // Demo
    update();
    <p id="scanned-QR">Text</p>
    <input id="code_id_value" type="text" name="" value="">

    Hope this helps! :)