フォームの入力文字数を,動的に表示するカウンタをjQueryで.
入力文字数制限のあるフォームに,動的に現在の入力文字数を表示するカウンタを付けたかったので,jQueryで書きました.
フレームワークはLaravel,テンプレートエンジンはbladeで.
$ vi app/routes.php
++ <?php
++
++ Route::get('word_count/input', function() {
++ return View::make('word_count/input');
++ });
$ vi app/views/word_count/input.blade.php
++ <html>
++ <head>
++ <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
++ <script src="/js/word_count.js"></script>
++ </head>
++ <body>
++ {{Form::open(['url' => 'word_count/confirm',])}}
++ {{Form::text('form_text', '', ['id' => 'form_text',])}}
++ <br>
++ <p id="word_counter"></p>
++ <br>
++ {{Form::submit('submit')}}
++ {{Form::close()}}
++ </body>
++ </html>
$ vi public/js/word_count.js
++ $(function() {
++ $('#form_text').count_word();
++ })
++
++ // フォームの入力文字数をカウント
++ $.fn.count_word = function() {
++ var word_length = $(this).val().length || 0;
++
++ // 初回表示時
++ display_word_counter(word_length);
++
++ $(this).bind('keydown keyup change', function() {
++ word_length = $(this).val().length;
++ display_word_counter(word_length);
++ })
++ }
++
++ // 文字数の表示
++ display_word_counter = function(word_length) {
++ $('#word_counter').text('').text(word_length + ' 文字');
++ }
こんなかんじでしょうか ><