Information

You appear to be using an unsupported browser, and it may not be able to display this site properly. You may wish to upgrade your browser.

Character count

A live count of the remaining permitted characters in an input field.

Sample HTML

<div class="ds_question" data-module="ds-character-count">
    <label class="ds_label" for="first-name">First name</label>
    <input maxlength="20" class="ds_input  ds_input--fixed-10" type="text" id="first-name" name="first-name">
</div>

About this component

A character count is an enhancement to standard text input and textarea components. It adds a live count of the remaining permitted characters so that the user knows how much they can type.

Why we use this component

The character count component tells users how much more they can type into a field.

A character count is better than only using a maxlength attribute on the input element. This is because:

  • it is non-destructive, so users can enter or paste too much data and get a warning instead of losing any of it
  • users can see how many characters they have remaining as they type

Other versions of this component

A percentage threshold can be set. The character count appears when a user types more characters than the threshol.

This example uses a threshold of 80%. The character count will show after the user types more than 240 characters out of 300. Remove some characters from the textarea to make the message disappear.

Sample HTML

<div class="ds_question" data-threshold="80" data-module="ds-character-count">
    <label class="ds_label" for="description">Description</label>
    <textarea maxlength="250" class="ds_input" rows="5" id="description" name="description">Mygov.scot gives people and businesses information about and access to public services in Scotland. We work closely with public sector organisations to make public services easy to find and understand.</textarea>
</div>

Implementation

A character limit can be set in two ways:

Maxlength attribute

You can use the maxlength attribute on the input element. This is a progressive enhancement. If the character count is not initialised for any reason the field will still have a character limit.

The component uses the value of this attribute to set its limit, then removes the attribute. This allows a user to type more than the input allows without losing any of their work. Instead, they will see a warning that they have exceeded the character limit.

data-maxlength attribute

You can use a data-maxlength attribute to set the character limit. This adds the character count but the field will not have the maxlength fallback for users who do not have JavaScript enabled.

Back to top