ドキュメント

Events/change

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

change( )

Triggers the change event of each matched element.
This causes all of the functions that have been bound to that change event to be executed, and calls the browser's default change action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the change event. The change event usually fires when a control loses the input focus and its value has been modified since gaining focus.

change( fn )

Binds a function to the change event of each matched element.
The change event fires when a control loses the input focus and its value has been modified since gaining focus.
Arguments:
fnFunction
A function to bind to the change event on each of the matched elements.
function callback(eventObject) {
  this; // dom element
}
Examples:

Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();

<!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(){
    
    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();

  });
  </script>
  <style>
  div { color:red; }
  </style>
</head>
<body>
  <select name="sweets" multiple="multiple">
    <option>Chocolate</option>
    <option selected="selected">Candy</option>
    <option>Taffy</option>
    <option selected="selected">Caramel</option>
    <option>Fudge</option>
    <option>Cookie</option>
  </select>
  <div></div>
</body>
</html>

To add a validity test to all text input elements:

$("input[type='text']").change( function() {
  // check input ($(this).val()) for validity here
});

NameType