0

enter image description here

Whenever I am putting some input in the input box, I am not able to get input from HTML. When I am doing console.log(text) it is blank.

<input type="number" id="text">

<script>
        var text = document.getElementById('text').value;
        console.log(text);
 </script>

1 Answers1

1

You are getting the input field's value on page load, which is a blank string since there is no value in the input at that time.

You can instead get the value when the input event is fired:

<input type="number" id="text">

<script>
text.addEventListener('input', function(){
  console.log(this.value)
})
 </script>

To store the value in a variable, you can assign the variable the value of the input field in the event listener:

<input type="number" id="text">

<script>
  var val;
  text.addEventListener('input', function() {
    val = this.value;
    console.log(val)
  })
</script>
Spectric
  • 30,714
  • 6
  • 20
  • 43