Reputation: 258
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>
Upvotes: 0
Views: 141
Reputation: 4434
document.getElementById("myButton").addEventListener("click", personData);
Updated: removed myButton
.
Upvotes: 2
Reputation: 2659
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);
Upvotes: 1