I tried .value , .textContent , innerText .... But nothing worked.... Below is my html
var input = document.getElementById('input').value var button = document.getElementById('submit') button.addEventListener('click', () => { console.log(input) /// Output is always blank })
<div class="input-section"> <input type="text" id="input" placeholder="Enter the word"> <button id="submit">Find</button> </div>
You need to read the value
property when the event fires, not before it.
let input = document.getElementById('input');
let button = document.getElementById('submit');
button.addEventListener('click',()=>{
console.log(input.value);
})
The reason why it is blank is because, you're initializing the input
variable with the initial value inside input, ie nothing.
When you click the button, you want the "current" value of input, which means that you'd have to find value on each button click.
Do it like this :
var button = document.getElementById('submit') button.addEventListener('click', () => { var input = document.getElementById('input').value; console.log(input); })
<div class="input-section"> <input type="text" id="input" placeholder="Enter the word"> <button id="submit">Find</button> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.