I’m working on a freeCodeCamp Javascript project and I currently need to obtain the value given by the user on my input element. I’m practically certain I have my code correct, yet when testing it on freeCodeCamp or in a Code Pen I created the value keeps returning as undefined
.
let cash = document.getElementById("cash").value;
const purchaseBtn = document.getElementById("purchase-btn");
purchaseBtn.addEventListener("click", () => {console.log(cash)});
2
Answers
This line:
is getting the value from the element immediately. Instead you want to cache only the element, and then log it’s value when the event handler is called.
listener are using other context to render value so the var cash is undefined for the listener execution
correction