Reputation: 101
I am trying to print the input text of a textarea to the console. The user would type a message then click a button and then the text would get printed to the console...
Here's my HTML:
<form action='/send_message' method='POST'>
<textarea name='message' id='message_box'></textarea>
<input name='receiver_id' type='text' id='number' style="display: none" value="{{info[0][0]}}">
<button id='btn' class='btn btn-primary' type='submit'>Message {{info[0][2]}}</button>
</form>
and here is the JS:
var message = $('textarea#message_box').val();
var button = document.getElementById('btn');
button.addEventListener('click',function(){
console.log(message)
});
The problem is that I get an empty message in the console no matter if the area is empty or containing text. I tried various combinations of val(), text, innerHTML but I pretty much always get the same empty output...
Upvotes: 1
Views: 2194
Reputation: 36574
You need to get the value of textarea when the button is clicked so assign the message
variable inside the event listener. Because we want to get the value of textarea each time button is clicked.
var button = document.getElementById('btn');
button.addEventListener('click', function() {
var message = $('textarea#message_box').val();
console.log(message)
});
Upvotes: 5