Skip to content

Instantly share code, notes, and snippets.

@dheerosaur
Created May 25, 2017 05:10
Show Gist options
  • Save dheerosaur/0cdb5f9d830d0b8e6759457470d07286 to your computer and use it in GitHub Desktop.
Save dheerosaur/0cdb5f9d830d0b8e6759457470d07286 to your computer and use it in GitHub Desktop.
Text input character counter
(function ($) {
function updateCharCount($obj, text, max_char) {
var contentLength = text.length;
$obj.find('.char-count').text(contentLength);
if (contentLength > max_char) {
$obj.removeClass('text-navy').addClass('text-danger');
} else {
$obj.removeClass('text-danger').addClass('text-navy');
}
}
$.fn.charCount = function(opts) {
var $this = $(this);
var max_length = $this.data('maxlength');
var max_char = max_length ? parseInt(max_length) : 1000;
var counterHTML = '<div class="counter"><span class="char-count">0</span> of <span>'+ max_length +'</span> characters</div>';
$this.after(counterHTML);
$this.on('keyup change', function(){
updateCharCount($this.next(), $this.val(), max_char);
});
updateCharCount($this.next(), $this.val(), max_char);
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment