ドキュメント

Events/keypress

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

keypress( )

Triggers the keypress event of each matched element.
This causes all of the functions that have been bound to the keypress event to be executed, and calls the browser's default keypress action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the keypress event. The keypress event usually fires when a key on the keyboard is pressed. The tab key is not trigger keypress in the IE browser.

keypress( fn )

Binds a function to the keypress event of each matched element.
The keypress event fires when a key on the keyboard is "clicked". A keypress is defined as a keydown and keyup on the same key. The sequence of these events is:
  • keydown
  • keypress
  • keyup
Arguments:
fnFunction
A function to bind to the keypress event on each of the matched elements.
function callback(eventObject) {
  this; // dom element
}
Examples:

Show spaces and letters when typed.

    $("input").keypress(function (e) {
      if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                        || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("p").append($("<span/>"))
              .children(":last")
              .append(document.createTextNode(c));
      } else if (e.which == 8) {
        // backspace in IE only be on keydown
        $("p").children(":last").remove();
      }
      $("div").text(e.which);
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("input").keypress(function (e) {
      if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                        || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("p").append($("<span/>"))
              .children(":last")
              .append(document.createTextNode(c));
      } else if (e.which == 8) {
        // backspace in IE only be on keydown
        $("p").children(":last").remove();
      }
      $("div").text(e.which);
    });

  });
  </script>
  <style>
  input { margin:10px; }
  p { color:blue; margin:10px; font-size:18px; }
  p.hilite { background:yellow; }
  div { color:red; }
  </style>
</head>
<body>
  <input type="text" />
  <p>Add text - </p>
  <div></div>
</body>
</html>

NameType