Agyan
adda
Run
Reset
Copy
jQuery Tutorial › jQuery Plugins › A simple character-counter plugin
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <textarea id="bio" rows="3" cols="40" placeholder="Short bio"></textarea> <br><br> <input id="title" size="40" placeholder="Post title"> <script> $.fn.charCounter = function (options) { const settings = $.extend({ max: 100, warnAt: 0.8 }, options); return this.each(function () { const $field = $(this).attr('maxlength', settings.max); const $count = $('<div>').css({ fontSize: '13px', color: '#666' }); $field.after($count); function update() { const len = $field.val().length; $count.text(len + ' / ' + settings.max) .css('color', len >= settings.max * settings.warnAt ? 'crimson' : '#666'); } $field.on('input', update); update(); }); }; $(function () { $('#bio').charCounter({ max: 150 }); $('#title').charCounter({ max: 60, warnAt: 0.9 }); }); </script>
Result