0

I'm trying that my script works when I click the button "Say It". But I cant make it work.

I know that I can put an onclick on the html but I need to do it with an addEventListener inside the script.

What am I doing wrong?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>First Thíngs</title>
  <style>
    input {
      font-size: 2em;
      margin: 10px 1px 0;
    }
  </style>
</head>
<body>
  <p>Your city: </p>
  <input class="city" type="text">
  <p>Your name: </p>
  <input class="name" type="text">
  <p></p>
  <button id="myButton">Say it !</button>

  <script>
    
    let city = document.querySelector(".city")
    let name = document.querySelector(".name")

    function personData(city, name){
    alert("I'm from " + city.value + " my name is " + name.value )
    }

    document.getElementById("myButton").myButton.addEventListener("click", personData);

  </script>
</body>
</html>

3
  • 3
    document.getElementById("myButton").myButton.addEventListener should be document.getElementById("myButton").addEventListener Commented Feb 23, 2021 at 11:43
  • Still not working. TypeError: Cannot read property 'value' of undefined at HTMLButtonElement.personData Commented Feb 23, 2021 at 11:46
  • 1
    That is because both city and name are undefined inside personData; that happens because the function expects to receive some arguments that you never pass to it, rather than reading the values from your input elements Commented Feb 23, 2021 at 11:50

2 Answers 2

2
document.getElementById("myButton").addEventListener("click", personData);

Updated: removed myButton.

Sign up to request clarification or add additional context in comments.

2 Comments

This won't work. You're passing the wrong arguments to the function
Error: TypeError: Cannot read property 'value' of undefined
1

Both city and name are undefined inside personData; that happens because the function expects to receive them as arguments rather than reading the values from your input elements... but you never passed those arguments.

You could change your JavaScript code as follow:

function personData() {
  let city = document.querySelector(".city");
  let name = document.querySelector(".name");

  alert("I'm from " + city.value + " my name is " + name.value)
}

document.getElementById("myButton").addEventListener("click", personData);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.