Huh...empty value from input?

html:

<body>
  <input type="text" id="input" placeholder="Search for...">
  <button>Click</button>
</body>

js:

const input = document.querySelector('#input');
const inputValue = input.value;
const button = document.querySelector('button');

button.addEventListener('click',()=>{
  console.log(inputValue);
});
const inputValue = document.querySelector('#input').value;
const button = document.querySelector('button');

button.addEventListener('click',()=>{
  console.log(inputValue);
});

I don’t get it, why can’t I get value using above two ways? Value keeps showing empty in console but with below code, I can…why??

const input = document.querySelector('#input');
const button = document.querySelector('button');

button.addEventListener('click',()=>{
  console.log(input.value);
});

Accessing .value outside of click listener set the value to empty value. Now if you type anything then click the listener is triggered but you’re not fetching .value in the listener in the first 2 cases. It should be inside the listener.

1 Like