Skip to content

Instantly share code, notes, and snippets.

Embed
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">
<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
You can’t perform that action at this time.