diff --git a/src/govuk/components/character-count/character-count.mjs b/src/govuk/components/character-count/character-count.mjs index 95239faccf..2ecb5c7103 100644 --- a/src/govuk/components/character-count/character-count.mjs +++ b/src/govuk/components/character-count/character-count.mjs @@ -54,6 +54,7 @@ var TRANSLATIONS_DEFAULT = { * @param {CharacterCountTranslations} [config.i18n = DEFAULT_TRANSLATIONS] */ function CharacterCount ($module, config) { + console.log('Creating CharacterCount') if (!$module) { return this } @@ -92,20 +93,20 @@ function CharacterCount ($module, config) { locale: closestAttributeValue($module, 'lang') }) + this.$module = $module + this.$textarea = $module.querySelector('.govuk-js-character-count') + this.$visibleCountMessage = null + this.$screenReaderCountMessage = null + this.lastInputTimestamp = null + + console.log(this.config) + // Determine the limit attribute (characters or words) if (this.config.maxwords) { this.maxLength = this.config.maxwords } else if (this.config.maxlength) { this.maxLength = this.config.maxlength - } else { - return } - - this.$module = $module - this.$textarea = $module.querySelector('.govuk-js-character-count') - this.$visibleCountMessage = null - this.$screenReaderCountMessage = null - this.lastInputTimestamp = null } /** @@ -120,6 +121,10 @@ CharacterCount.prototype.init = function () { var $textarea = this.$textarea var $fallbackLimitMessage = document.getElementById($textarea.id + '-info') + 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) diff --git a/src/govuk/components/character-count/character-count.test.js b/src/govuk/components/character-count/character-count.test.js index 0c95ea8992..40c077ded8 100644 --- a/src/govuk/components/character-count/character-count.test.js +++ b/src/govuk/components/character-count/character-count.test.js @@ -433,6 +433,28 @@ describe('Character count', () => { const visibility = await page.$eval('.govuk-character-count__status', el => window.getComputedStyle(el).visibility) expect(visibility).toEqual('visible') }) + + it.only('injects the description of the textarea', async () => { + page.on('console', async (e) => { + const args = await Promise.all( + e.args().map((a) => a.jsonValue()) + ) + console[e.type() === 'warning' ? 'warn' : e.type()](...args) + }) + + 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`', () => {