开发者

Getting events one character at a time in Javascript

I'm pretty new to Javascript, so bear with me if this is obvious.

Basically what I would like is to implement a little interface where when you type something in a textbox it gives an event. Sort of like how this stack overflow post preview works.开发者_如何学Python I tried hooking into the OnChange event, but that only gives an event when they are done editing the field(and the textbox loses focus). What I want is each time they do anything to the text inside the textbox to get an event..


You want the keypress events described here.


Oh, try the onkeydown event.

Here's a dumb example:

<html>
<body>
<form action="" method="POST" id="myForm">
<input type="text" name="myText" onkeydown="doAlert(event);"/>

<script type="text/javascript" language="JavaScript">

function doAlert(e) {

  if(window.event)
  {
      alert( window.event.keyCode);
  }
  else if(e)
  {
      return alert(e.which);
  }
  else
  {
      return null;
  }

}

</script>
</form>
</body>
</html>


You may try the onkeyup event:

<html>
<head>
    <title>Test</title>
</head>
<body>

<input type="text" name="test" value="" onkeyup="javascript:document.getElementById('preview').innerHTML = this.value;" />

<div id="preview"></div>

</body>
</html>


onkeypress might be what you want.


Try binding to one of the following events: onkeydown, onkeypress or onkeyup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜