Skip to content

Instantly share code, notes, and snippets.

@thatdevgirl
Last active December 19, 2019 20:08
Show Gist options
  • Save thatdevgirl/c4e3199869258224353a5ecaf2fee271 to your computer and use it in GitHub Desktop.
Save thatdevgirl/c4e3199869258224353a5ecaf2fee271 to your computer and use it in GitHub Desktop.
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">
<head>
<title>Character Count using jQuery</title>
</head>
<body>
<header>
<h1>Character Count using jQuery</h1>
</header>
<main>
<textarea class="countMe"></textarea>
</main>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="character-counter.js"></script>
<script>
$( '.countMe' ).characterCount( 250 );
</script>
</body>
</html>
// 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.
this.after(
'<div class="characterCount">' +
'(<span>' + remaining + '</span> characters remaining)' +
'</div>');
// 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