From 1a62c29460813aff64bf76e06dc7095ec0fe12b4 Mon Sep 17 00:00:00 2001 From: Romaric Date: Mon, 17 Oct 2022 15:30:12 +0100 Subject: [PATCH] Make CharacterCount's JS inject fallback hint if missing --- .../character-count/character-count.mjs | 8 ++++++++ .../character-count/character-count.test.js | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/govuk/components/character-count/character-count.mjs b/src/govuk/components/character-count/character-count.mjs index 95239faccf..74b57d43d5 100644 --- a/src/govuk/components/character-count/character-count.mjs +++ b/src/govuk/components/character-count/character-count.mjs @@ -120,6 +120,13 @@ CharacterCount.prototype.init = function () { var $textarea = this.$textarea var $fallbackLimitMessage = document.getElementById($textarea.id + '-info') + // Inject a decription for the textarea if none is present already + // for when the component was rendered with no maxlength, maxwords + // nor custom fallbackHintText + if ($fallbackLimitMessage.textContent.match(/^\s*$/)) { + $fallbackLimitMessage.textContent = this.i18n.t('fallbackHint', { count: this.maxLength }) + } + // Move the fallback count message to be immediately after the textarea // Kept for backwards compatibility $textarea.insertAdjacentElement('afterend', $fallbackLimitMessage) @@ -373,4 +380,5 @@ export default CharacterCount * @property {import('../../i18n.mjs').PluralisedTranslation} [wordsUnderLimit] * @property {string} [wordsAtLimit] * @property {import('../../i18n.mjs').PluralisedTranslation} [wordsOverLimit] + * @property {import('../../i18n.mjs').PluralisedTranslation} [fallbackHint] */ diff --git a/src/govuk/components/character-count/character-count.test.js b/src/govuk/components/character-count/character-count.test.js index 0c95ea8992..7694a48088 100644 --- a/src/govuk/components/character-count/character-count.test.js +++ b/src/govuk/components/character-count/character-count.test.js @@ -433,6 +433,21 @@ describe('Character count', () => { const visibility = await page.$eval('.govuk-character-count__status', el => window.getComputedStyle(el).visibility) expect(visibility).toEqual('visible') }) + + it('injects the description of the textarea', async () => { + await renderAndInitialise(page, 'character-count', { + nunjucksParams: examples['no maximum'], + javascriptConfig: { + maxlength: 10 + } + }) + + const message = await page.$eval( + '.govuk-character-count__message', + (el) => el.innerHTML.trim() + ) + expect(message).toEqual('No more than 10 characters') + }) }) describe('via `initAll`', () => {