Skip to content

Commit

Permalink
Make CharacterCount's JS inject fallback hint if missing
Browse files Browse the repository at this point in the history
  • Loading branch information
romaricpascal committed Oct 18, 2022
1 parent 719d880 commit 1a62c29
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/govuk/components/character-count/character-count.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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]
*/
15 changes: 15 additions & 0 deletions src/govuk/components/character-count/character-count.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`', () => {
Expand Down

0 comments on commit 1a62c29

Please sign in to comment.