Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript how to log the value a user has put in?

The problem given was:

When the user clicks the button with the ID of generate-message, log the value the user has typed into the input field.

Here is the HTML provided:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <input type="text" id="message">
 <button id="generate-message">Express Yourself!</button>

I have tried multiple things, my most recent attempt was:

 const button = document.getElementId("generate-message")
 button.addEventListener("click", function(){
 })

>Solution :

Welcome to StackOverflow!

You’re first attempt was a good start!
Firstly, the function to get an element by it’s ID is getElementById, not getElementId. You will likely have been getting errors using the wrong function name.

Once you have the button’s event listener set up, you can put whatever code inside it you like. You can use functions like console.log() or alert() to see the contents of a variable.

Have a good go at it yourself, but if you are really struggling, here’s how you could do it:

const button = document.getElementById("generate-message")
 const input = document.getElementById("message")
 
 button.addEventListener("click", function(){
  const val = input.value;
  console.log(val);
  alert("Your value is: " + val)
 })
<input type="text" id="message">
<button id="generate-message">Express Yourself!</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading