Search code examples
javascriptonkeypress

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


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/


Solution

  • 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>