javascriptinput

Why won't my function capture the value of my input element?


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)});

Solution

  • This line:

    const cash = document.getElementById('cash').value;
    

    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.

    const cash = document.getElementById('cash');
    
    const purchaseBtn = document.getElementById('purchase-btn');
    
    purchaseBtn.addEventListener('click', () => {console.log(cash.value)});
    <input id="cash">
    <button type="button" id="purchase-btn">Click me</button>