0

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>

1
  • Also for the future, never call anything in a form "submit". If you want to submit the form using script you will not be able to unless you rename the button Commented Sep 30, 2020 at 9:52

2 Answers 2

1

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);
})
Sign up to request clarification or add additional context in comments.

Comments

0

The reason why it is blank is because, you're initializing the input variable with the initial value inside input, i.e. 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.