Search code examples
javascriptaddeventlistener

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:

 <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

  • 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>