js、jQueryで入力の都度、残りの文字数を出力

目次

js、jQueryで入力の都度、残りの文字数を出力

フォームのテキスト内に文字が入力されるたびに、残りの入力可能文字数を変動させたい。

HTML、js、jQueryソース

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/jquery-3.7.0.min.js"></script>
    <title>Document</title>
</head>
<script>
   $(function(){
        //  初期時表示時
        count = $("#text1").val().length;   // テキストの文字数を取得
        $(".strzan").text(100 - count);     // 最大文字数 - 取得した文字数をstrzanクラスが付与されたspanタグにセット

        //  テキストが変化するたびにfunction内の処理を実行
        $("#text1").bind("input", function(){
            count =$("#text1").val().length;  // テキストの文字数を取得
            zan = 100-count;                  // 最大文字数 - 取得した文字数を変数.zanに格納
            if(zan < 0){                      // 変数.zanが0未満の場合、0をセット
                $(".strzan").text(0);	
            }else{                            // その他の場合、計算結果をセット
                $(".strzan").text(zan);
            }
        });
    });
</script>
<body>
    <form action="" method="">
        残りの入力可能文字数を出力:
        <input type="text" id="text1" name="" value="" size="40" maxlength="100"> 
        <span id="strzan"   class="strzan align-bottom"></span>
        <span id="strtotal" class="align-bottom">/100</span>
    </form>
</body>
</html>
  • URLをコピーしました!
目次