jquery テキストフォームの変更を取得する

jquery テキストフォームの変更を取得する

jqueryで、テキストフォームの変更を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 91.0.4472.77

テキストフォームの変更を取得

テキストフォームの変更を取得するには「change」を使用します。
テキストフォームの値を変更すると、用意したテキストを表示するサンプルコードを記述してます。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <!-- semantic.js  -->
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }
</style>
<script>

  $(function () {
    $("#txt").change(function () {

      $("#msg").text('テキストが変わりました')

    });
  });

</script>

<body>

  <div class="ui middle aligned center aligned grid">
    <div class="column">

      <form class="ui fluid form">
        <div class="inline field">

          <input id="txt" type="text" placeholder="入力してください">
          <div id="msg" class="ui left pointing red basic label"></div>
          
        </div>
      </form>

    </div>
  </div>
</body>

</html>

変更されたことが取得できていることが確認できます。

また、以下のようにアロー関数を使用して記述することも可能です。
※アロー関数を使用するとthisの挙動が異なります。

$(() => {
  $("#txt").change(() => {

    $("#msg").text('テキストが変わりました')

  });
});