How to Count Characters with jQuery
jQuery makes it easy to attach a live character counter to any textarea or input in two lines of code. This tutorial covers the basic pattern plus enhanced versions with max-length, color changes, and a comparison with vanilla-JS alternatives. For a modern, dependency-free version see our JavaScript tutorial or the React-component version in our React tutorial.
Basic live character counter
Two-line version — attach a keyup handler to the input and update a counter element.
$('#text').on('keyup input', function() {
$('#counter').text($(this).val().length + ' characters');
});With HTML
Complete example with markup.
<textarea id="text" maxlength="280" rows="4"></textarea>
<span id="counter">0 / 280</span>
<script>
$(function() {
const $text = $('#text');
const $counter = $('#counter');
const max = parseInt($text.attr('maxlength'), 10);
$text.on('input', function() {
const len = $(this).val().length;
$counter.text(len + ' / ' + max);
});
});
</script>With max-length warning
Change color when approaching the limit.
$('#text').on('input', function() {
const len = $(this).val().length;
const max = 280;
const remaining = max - len;
const $counter = $('#counter');
$counter.text(remaining + ' remaining');
if (remaining < 0) {
$counter.css('color', 'red');
} else if (remaining < 20) {
$counter.css('color', 'orange');
} else {
$counter.css('color', 'gray');
}
});Multiple counters from one handler
Attach to every textarea on the page with data attributes.
// HTML:
// <textarea data-max="280" data-counter="tweetCount"></textarea>
// <span id="tweetCount"></span>
$('textarea[data-max]').on('input', function() {
const $this = $(this);
const max = parseInt($this.data('max'), 10);
const counterId = $this.data('counter');
const len = $this.val().length;
$('#' + counterId).text(len + ' / ' + max);
});Modern vanilla-JS equivalent (no jQuery)
If you don't already use jQuery, vanilla JS is simpler. Same functionality, no dependency.
const text = document.querySelector('#text');
const counter = document.querySelector('#counter');
text.addEventListener('input', () => {
counter.textContent = `${text.value.length} characters`;
});Common Pitfalls
⚠Don't load jQuery just for a character counter
If you don't already have jQuery on the page, the vanilla JS version is shorter, faster, and avoids a 90KB dependency.
⚠Use 'input', not 'keyup'
'keyup' misses paste events and contextual menu actions. 'input' fires reliably on every value change — including paste, cut, and drag-drop.
⚠Don't enforce maxlength client-side only
Server-side validation is mandatory. Client-side limits are convenience, not security.
⚠Watch out for jQuery global conflicts
If multiple libraries claim '$', use jQuery's noConflict() mode or alias jQuery to a different variable.
See a Working Character Counter
Our Character Counter is built using the patterns from this tutorial. Open the dev tools to inspect the live implementation.
📊Open Character Counter