Problem:
I have an input element in my html code and I want to access toits value but my javascript code doesn’t work.
Does anyone have an answer to this ?
let inputElem = document.getElementById('username');
let button = document.getElementById('input-btn');
let inputValue = inputElem.value;
button.addEventListener('click', function () {
console.log(inputValue);
});
<input type="text" id="username">
<button type="button" id="input-btn">click</button>
Solution:
You’re reading the value immediately upon loading the page, before the user has had a chance to enter a value.
Read the value in the click handler instead:
let inputElem = document.getElementById('username');
let button = document.getElementById('input-btn');
button.addEventListener('click', function () {
let inputValue = inputElem.value;
console.log(inputValue);
});
<input type="text" id="username">
<button type="button" id="input-btn">click</button>