zokanzi
zokanzi

Reputation: 117

Get value from div to textbox

Is there a way to get the value from a div element to textbox?

My script codes

$(document).ready(function() {
    barcode.setHandler(function(barcode) {
        $('#result').html(barcode);
    });
    barcode.init();

I show the result with the following code

<div id="result"></div>

I fail to get the div value into the textBox.

 <input type="text" id="result">

Upvotes: 0

Views: 1415

Answers (2)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use below option

Avoid using same id for multiple elements , instead of that use class or two different ids or use one as class and for other use as id

$(document).ready(function() {
console.log( $('#result').text())
        $('.result').val( $('#result').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">1222</div>
<input type="text" class="result">

code sample - https://codepen.io/nagasai/pen/yjomXp

Upvotes: 1

larz
larz

Reputation: 5766

Ids need to be unique on a given page; your input and div both have the same id. To insert from the div to the input, first get the text inside the div, then apply that to the input using .val().

const foo = $('#foo').text();
$('#bar').val(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  This is inside the div
</div>
<input type="text" id="bar"></input>

Upvotes: 1

Related Questions