Skip to main content

Character count

A live count of the remaining permitted characters in an input field so that the user knows how much they can type.

About this component

A character count is an enhancement to standard text input and textarea components.

Why we use this component

If a form field only allows a certain number of characters to be entered, it is helpful to let the user know how many remaining characters they are allowed.

You can enter up to 20 characters.

HTML

                                
                                    
<form> <div class="form-group mb-3 mt-3"> <label class="form-label" for="first-name"> First name </label> <!-- Hint text + character count status --> <p class="form-hint--text"> You can enter up to 20 characters. <span id="first-name-status" aria-live="polite"></span> </p> <input type="text" id="first-name" name="first-name" maxlength="20" aria-describedby="first-name-hint first-name-status" class="form-control" > </div> </form>

CSS

                                
                                    
/* Character count ------------------------------------ */ .character-count--entered { float: right; color: var(--scottish-dark-teal); margin-right: 10px; } .character-count--remaining { float: right; color: var(--scottish-dark-teal); }

JavaScript

                                
                                    
(function () { const input = document.getElementById("first-name"); const status = document.getElementById("first-name-status"); const max = parseInt(input.getAttribute("maxlength"), 10); const updateCount = () => { const length = input.value.length; const remaining = max - length; // Update with meaningful text for screen readers status.textContent = remaining === 1 ? "1 character remaining" : `${remaining} characters remaining`; }; // Initialise counter on page load updateCount(); // Update counter on each keystroke input.addEventListener("input", updateCount); })();