user90726
user90726

Reputation: 975

Get text from dynamically-filled textarea

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>

Upvotes: 1

Views: 34

Answers (3)

bogdanoff
bogdanoff

Reputation: 2358

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>

Upvotes: 1

Brother58697
Brother58697

Reputation: 3178

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>

Upvotes: 1

Omid_Mirzaee_Yazdi
Omid_Mirzaee_Yazdi

Reputation: 90

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);
});

Upvotes: 0

Related Questions