Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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)を表示させる

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away