How to call function from text input key press in javascript?

abalter picture abalter · Mar 1, 2015 · Viewed 31.9k times · Source

With

<input type="text" onKeyPress="alert(this.value)">

the alert box displays the value in the box, not included the current key depressed.

However, this does not exhibit the same behavior, and I don't know why.

<input type="text" onKeyPress="handleInput(this.value)">

function handleInput(value){
    alert(value);
}

Added This http://jsfiddle.net/abalter/adbbb599/6/

Answer

ismnoiet picture ismnoiet · Mar 1, 2015

First thing is avoid using js code inside html tags it is a bad practice , you can use the keyup event to get the content of the input after the user release any pressed key

<input id="input">

<script>
  var input = document.getElementById('input');
  input.addEventListener('keyup',function(){alert(input.value);});

</script>