10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryを使って文字数カウントを表示させる方法

Posted at

textareaなどでjQueryを使って文字数カウントを表示する方法を紹介します。

まずはコードから

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
 <meta charset="utf-8">
 <title>sample</title>
</head>
<body>

<textarea id="js-count" rows="10" cols="100"></textarea>
        <div class="counter">
          <span class="show-count">0</span>文字
        </div>

<script src="https://code.jquery.com/jquery-3.3.1.js">
</script>
<script src="js/app.js">
</script>
</body>
</html>
app.js

$(function(){

  $('#js-count').keyup(function(){
    var count = $(this).val().length;
    $('.show-count').text(count);
  });
});
  • 文字数を取得したいところのid属性やclass属性を入力してノードを取ってくる(ここでは#js-count)

  • keyupメソッドを使ってキーを離した時に処理が走るようにする

  • 変数(ここではcount)の中に文字数の値を入れる

  • 文字を表示したい場所(ここでは.show-count)を指定して.textで値(count)を表示させる

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?