Skip to content

Instantly share code, notes, and snippets.

Last active December 19, 2019 20:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
This component is a simple jQuery function that adds a character counter to a form field. The function takes a single parameter - the character limit of the specified form element.
<!DOCTYPE html>
<html lang="en">
<title>Character Count using jQuery</title>
<h1>Character Count using jQuery</h1>
<textarea class="countMe"></textarea>
<script src=""></script>
<script src="character-counter.js"></script>
$( '.countMe' ).characterCount( 250 );
// Append a character count element in the DOM.
$.fn.characterCount = function(max) {
if (this.val() == undefined) { return false; }
// Calculate remaining characters based on the initial value of the field.
var remaining = max - this.val().length;
// Display initial remaining character count message.
'<div class="characterCount">' +
'(<span>' + remaining + '</span> characters remaining)' +
// Set the max length of the text area.
this.attr('maxlength', max);
// Keyup event to update remaining character count message.
var parent = this.parent();
this.keyup(function() {
var remaining = max - $(this).val().length;
$('.characterCount span', parent).html(remaining);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment