Mrinal Anand
Mrinal Anand

Reputation: 65

Output contents of HTML Element into console

I know only a little bit of JavaScript. I need to output in my terminal a message input by user in a html form, but my current JavaScript solution isn't displaying the right output.

HTML

<h2 class="heading">Send e-mail to [email protected]:</h2>
<input name="myText" id="myText" type="text" placeholder="enter your message here">
<button id="btn" onclick="sendMail()">Send</button>
<script src="./server.js"></script>

javascript

console.log(document.getElementById('myText').innerText());

Upvotes: 2

Views: 1248

Answers (3)

Professor Abronsius
Professor Abronsius

Reputation: 33804

Presumably you wish to get the value from the text field when some sort of event occurs? Assign an event handler to the input element - like so:

document.querySelector('input[name="myText"]').addEventListener('keyup',function(e){
  console.log(this.value)
})
<h2 class="heading">Send e-mail to [email protected]:</h2>
<input name="myText" id="myText" type="text" placeholder="enter your message here">
<button id="btn" onclick="sendMail()">Send</button>

To assign an event handler to the button

document.querySelector('button#btn').addEventListener('click',function(e){
  e.preventDefault();
  console.log(this.previousElementSibling.value)
})
<h2 class="heading">Send e-mail to [email protected]:</h2>
<input name="myText" id="myText" type="text" placeholder="enter your message here">
<button id="btn">Send</button>

Upvotes: 2

Kirill Savik
Kirill Savik

Reputation: 1278

You can use JQuery.

$(':input').keyup(function() {
    console.log($(this).val())
});

Upvotes: 2

Endrit Shabani
Endrit Shabani

Reputation: 190

Use this and you get the value inside input

document.getElementById('myText').value

Upvotes: 3

Related Questions