How to copy content from a div to an input?

Asked

Viewed 204 times

0

I’m trying to copy content from a div to an input. I’ve been able to copy from one input to another or from one div to another, but I couldn’t get from one div to an input.

<div id="teste">
  Exemplo
</div>
<input id="texto" />

What I got was :

<div id="teste">
  Exemplo dasjkhd kdhasj khd askjh
</div>
<div id="texto"></div>

<script>// Elemento com o Texto
var elemento = document.getElementById('teste').innerHTML;
// Escrevendo em outro Elemento
var texto = document.getElementById('texto');
texto.innerHTML = "Texto Copiado: " + elemento;
</script>
  • 1

    input does not have property innerHTML, try using the property value, by the way, put the type of input, text, for example

  • It worked, now would be able to update automatically without needing to update the page?

  • 1

    can put the script in the event onchange of the div

  • It worked out, thank you very much

2 answers

2

// Elemento com o Texto
var elemento = document.getElementById('teste').innerHTML;
// Escrevendo em outro Elemento
var texto = document.getElementById('texto');
texto.value = "Texto Copiado: " + elemento;
<div id="teste">
  Exemplo
</div>
<input id="texto" />

  • It worked, now would be able to update automatically, without needing to update the page? because this div turns into a textarea

1


It worked, now would be able to update automatically, without needing update the page? because this div becomes a textarea

You can add a Listener that observes the modifications in the element and update the input content:

// Elemento com o Texto
var elemento = document.getElementById('teste');
var texto = document.getElementById('texto');
  elemento.addEventListener('DOMSubtreeModified', function () {
  var elemento = this.innerHTML;
  // Escrevendo em outro Elemento
  texto.value = "Texto Copiado: " + elemento;
})
<div id="teste" contentEditable="true" style="height:50px; border: 1px dashed #ccc; margin: 5px 0">
  CLIQUE PARA EDITAR O TEXTO
</div>
<input id="texto" />

EDIT:

I saw that this method is "deprecated", there are other options, one of them is to change the name of the DOMSubtreeModified for input

// Elemento com o Texto
var elemento = document.getElementById('teste');
var texto = document.getElementById('texto');
  elemento.addEventListener('input', function () {
  var elemento = this.innerHTML;
  // Escrevendo em outro Elemento
  texto.value = "Texto Copiado: " + elemento;
})
<div id="teste" contentEditable="true" style="height:50px; border: 1px dashed #ccc; margin: 5px 0">
  CLIQUE PARA EDITAR O TEXTO
</div>
<input id="texto" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.