skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. listener are using other context to render value so the var cash is undefined for the listener execution

    correction

    const purchaseBtn = document.getElementById("purchase-btn");
        purchaseBtn.addEventListener("click", () => {
            let cash = document.getElementById("cash").value;
            console.log(cash
        );
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search