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

帅比萌擦擦* 提交于 2019-12-11 10:41:04

问题


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/


回答1:


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>



回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/28788896/how-to-call-function-from-text-input-key-press-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!