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

后端 未结 3 1595
耶瑟儿~
耶瑟儿~ 2021-01-24 05:38

With


the alert box displays the value in the box, not included the current key dep

相关标签:
3条回答
  • 2021-01-24 06:02

    Passing 'value' as a parameter is generally verbotim - its a reserved word. Your 'this' refers to the input field, and so 'this.value' returns the entire content of the input field. To get the keyCode from the keypress event try:

    <body>
    <input type="text" onKeyPress="handleInput();">
    </body>
    <script>
    function handleInput(){
        alert(event.charCode);
    }
    </script>
    

    This doesn't work with:

    onKeyPress="event.charCode;"
    

    or:

    onKeyPress="this.event.charCode;"
    

    because no event object is created.

    0 讨论(0)
  • 2021-01-24 06:10

    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>
    
    0 讨论(0)
  • 2021-01-24 06:14

    It should exhibit the same behaviour. Make sure you load the javascript either in your head or body tags, so you can access the function from the html.

    This code works for me:

    <input type="text" onKeyPress="handleInput(this.value)">
        <script>
            function handleInput(value){
                alert(value);
            }
        </script>
    
    0 讨论(0)
提交回复
热议问题