The character count component provides a count mechanism for character count limited text areas. See updated @uol-form-input for implementation.
This component should only be used within the @uol-form-input component where it is used for the type “textarea”.
Do not use in any other situations.
The max length is inherited form the parent @uol-form-input component.
The character count is for user information only and will not prevent form submission. Any hard limits should be enforced with post submission validation and the form returned with an input error.
<p class="uol-form__input--character-count" id="{{ id }}-char-count">{{maxlength}} character limit</p>
<p class="uol-form__input--character-count" id="charCountID-char-count">50 character limit</p>
.uol-form__input--character-count {
@extend %text-size-paragraph--small;
padding-top: $spacing-3;
font-weight: 500;
margin: 0;
user-select: none;
font-variant-numeric: lining-nums;
@include media(">=uol-media-m") {
font-weight: 400;
}
&[data-field-invalid="true"] {
color: darken($color-alert--error, 5%);
}
}
.uol-form-input__excess-text {
background-color: lighten($color-alert--error, 30%);
font-style: normal;
}
export const displayRemainingCharacters = () => {
const hasCharCount = document.querySelectorAll('[data-char-limit="true"]');
hasCharCount.forEach( (input) => {
const maxLength = input.getAttribute('data-maxlength');
const charCountText = input.closest('.uol-form__input--textarea-wrapper').nextElementSibling;
charCountText.innerText = `${maxLength} character limit`;
const ariaLiveRegion = document.querySelector('.uol-form__announcement');
input.addEventListener('input', () => {
charCountText.setAttribute('data-field-invalid', 'false');
input.parentElement.setAttribute('data-field-invalid', 'false');
const charText = ((maxLength - input.value.length) == - 1 || (maxLength - input.value.length) == 1) ? 'character' : 'characters';
if (input.value.length > 0 && input.value.length <= maxLength) {
charCountText.innerText = `You have ${maxLength - input.value.length} ${charText} remaining`;
} else if (input.value.length == 0) {
charCountText.innerText = `${maxLength} character limit`;
} else if (input.value.length > maxLength) {
charCountText.setAttribute('data-field-invalid', 'true')
input.parentElement.setAttribute('data-field-invalid', 'true');
charCountText.innerText = `You have ${input.value.length - maxLength} ${charText} too many`;
}
ariaLiveRegion.innerText = charCountText.innerText;
})
})
}
{
"maxlength": 50,
"id": "charCountID"
}