14
10

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.

【JavaScript】リアルタイムで文字数をカウントして表示させる(要jQuery)

Last updated at Posted at 2018-01-11

文字数に制限があって、残り何文字入力できるのかを表示する必要がある場合は使えるかもしれません。
(※別途バリデートかける必要があります)

form.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script type="text/javascript">
$(function(){

    var text_max = 10; // 最大入力値
    $(".count").text(text_max - $("#memo_text").val().length);

    $("#memo_text").on("keydown keyup keypress change",function(){
        var text_length = $(this).val().length;
        var countdown = text_max - text_length;
        $(".count").text(countdown);
        // CSSは任意で
        if(countdown < 0){
            $('.count').css({
                color:'#ff0000',
                fontWeight:'bold'
            });
        } else {
            $('.count').css({
                color:'#000000',
                fontWeight:'normal'
            });
        }
    });
});
</script>

<!-- 略 -->

<b>Text内容</b><span class="count"></span>文字
<br><textarea name="memo_text" id="memo_text" cols="50" rows="10"></textarea>

↓実際の動きとしてはこんな感じです
count.gif

CodePen

See the Pen text count by sola-msr (@sola-msr) on CodePen.

14
10
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
14
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?