Get text from dynamically-filled textarea

Viewed 24

The issue seems to be simple, but I really don't understand. Why the alert window is blank after I type something in the textarea and press the button?

const source = document.querySelector('textarea#source').textContent;
  
document.querySelector('button').addEventListener('click', function() {
  alert(source);
});
<textarea id="source" rows="25"></textarea>
<button>click me</button>

3 Answers

You need to change two things. First, the property you need is value not textContent.

But we don't just replace it because by declaring

const source = document.querySelector('textarea#source').value;

we're setting source to a string by value not by reference. Which means that we're taking what the value is at that moment and set it.So instead, we just set source to reference the element object itself, since setting variables to objects is done by reference.

const source = document.querySelector('textarea#source') // The textArea element

Then when event triggers, our handler calls source.value:

const source = document.querySelector('textarea#source'); // The textArea element
  
document.querySelector('button').addEventListener('click', function() {
  alert(source.value);
});
<textarea id="source" rows="25"></textarea>
<button>click me</button>

const source = document.querySelector('textarea#source').textContent

Above line won't mutate when DOM content changes, because its no longer an object. Its just a string (only object like datatypes can mutate) so, do this intead.

const inp = document.querySelector('#source') //document.getElementById('source')

document.querySelector('button').addEventListener('click', function() {
  console.log(inp.textContent)
});
<div id="source" contenteditable>
  hello
</div>
<hr/>
<button>check</button>

I think its because the value of source is defined when that block of code is loaded while the alert is triggered onclick, try this approach and see if it works

document.querySelector('button').addEventListener('click', function() {
  const source = document.querySelector('textarea#source').textContent;
  alert(source);
});
Related