How can I display the input value?

Viewed 34

I would like to show what I write in the input, but everytime I try the alert window shows "undefined". This is the code. Thanks.

<body>
    <input id="input"></input>
    <button id="search">search</button>
   
    <script>
        document.getElementById('search').addEventListener("click", show);
        var input = getElementById('input');
        var search = input.value;
        function show() {
          alert(search);
        }
    </script>
</body>
2 Answers

you must bring var search into show function declaration in order to get new value of search box every time the event occurs.

function show(){
  var search = input.value;
  alert(search);
}

First you need to use document.getElementById instead of just getElementById. Then you need to put var search = input.value inside the show function so that it gets the current value each time you want to show it, and not just the initial one.

document.getElementById('search').addEventListener("click", show);
var input = document.getElementById('input');

function show() {
  var search = input.value;
  alert(search);
}
<input id="input"></input>
<button id="search">search</button>

Related