Problem on Passing getElementById value to textbox Value

Viewed 97

I can see the scanned value (id="code") on p element. How can I fill the textbox with this value?

Actually when I press the Scan Barcode button, camera is open and scan an EAN13 barcode, and the value is shown in P element (590123... is the barcode). Can be seen below. But I want to see this value in textbox.

wrong output

function barcode() {
  var resultElement = document.getElementById("code");
 // setupLiveReader(resultElement)
}
<p id="code">code is appearing here</p>

<input class="form-control" type="text" id="code">
<button onclick="barcode()" type="submit" class="btn btn-primary btn-sm">Scan Barcode</button>

3 Answers

Change the id so that you only have one id="code", then update the script so resultElement has the id of the <input...

<p id="code">code is appear here</p>

<input class="form-control" type="text" id="code-input">
<button  onclick="barcode()" type="submit" class="btn btn-primary btn-sm">Scan Barcode</button>

<script>
   function barcode() {
       const resultElement = document.getElementById("code-input");
       setupLiveReader(resultElement);
   }  
</script>

You can't have two elements with the same id. To get the content of the p tag just call innerHTML on it. After that set the value of your input with the new id.

<p id="code">code is appear here</p>

<input class="form-control" type="text" id="codeInput">
<button  onclick="barcode()" type="submit" class="btn btn-primary btn-sm">Scan Barcode</button>

<script>
function barcode() {
    var resultElement = document.getElementById("code").innerHTML;
    //setupLiveReader(resultElement)
    document.getElementById("codeInput").value = resultElement;
}  
</script>

function getValue() {
    var resultInputValue = document.getElementById("inputValue").value;
    document.getElementById("valueShow").innerHTML = resultInputValue;
}  
<p id="valueShow">input value is appear here</p>

<input type="text" id="inputValue">
<button  onclick="getValue()" type="submit">Get Value</button>

Related