skip to Main Content

I’m trying to get the value of my input by the following simple code but nothing is printed in **result **box.

<body>
<div id="result" style="height:100px"></div>
<hr>
<input type="text" id="inp">
<script>
let inp = document.getElementById('inp');
let result = document.getElementById('result');
result.textContent = inp.value;
</script>
</body>

I was expecting that whatever I enter in the input box, is printed in result box.

2

Answers


  1. Add an event listener for the "input" event to get notified each time the value changes.

    Currently, you are reading the value only once, on page load when the user has not entered anything yet.

    let inp = document.getElementById('inp');
    let result = document.getElementById('result');
    inp.addEventListener('input', e => result.textContent = inp.value);
    <div id="result" style="height:100px"></div>
    <hr>
    <input type="text" id="inp">
    Login or Signup to reply.
  2. Simply using oninput(Whatever I enter in the input box) method:

    let inp = document.getElementById('inp');
    let result = document.getElementById('result');
    
    inp.oninput = function() {
      result.textContent = inp.value;
    }
    <div id="result" style="height:100px"></div>
    <hr>
    <input type="text" id="inp">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search