From 3b52b27a34d03de78645cf6f7ab1aed43b2e3f0e Mon Sep 17 00:00:00 2001 From: Hanna Laakso Date: Thu, 26 Sep 2019 12:15:24 +0100 Subject: [PATCH] Make count message required MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The count message always exists (since https://github.com/alphagov/govuk-frontend/commit/7b534bf734cd0a1be2cff34d64018aa89abdabb6). This PR makes the markup for it required, instead of giving the option to add it with JS since the user needs to be informed of the limit in the number of characters they can type in even if JS doesn’t run. The count message DOM element is now defined at the top of the module with the other required DOM elements. We check whether the textarea is present before trying to its id to find the count message - the check prevents a DOM search error for `$textarea.id` if the script is run without component markup being present present on the page. Alternatively we could define the count message in `init()` after doing a check for textarea which would require another check for it and wouldn’t make it as clear that it’s required as when placed at the top of module. ``` CharacterCount.prototype.init = function () { var $module = this.$module var $textarea = this.$textarea if (!$textarea) { return } this.$countMessage = $module.querySelector('[id=' + this.$textarea.id + '-info]') if (!$countMessage) { return } ``` --- src/govuk/components/character-count/character-count.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/govuk/components/character-count/character-count.js b/src/govuk/components/character-count/character-count.js index b7e421294b..c4549dc658 100644 --- a/src/govuk/components/character-count/character-count.js +++ b/src/govuk/components/character-count/character-count.js @@ -5,6 +5,7 @@ import '../../vendor/polyfills/Element/prototype/classList' function CharacterCount ($module) { this.$module = $module this.$textarea = $module.querySelector('.govuk-js-character-count') + if (this.$textarea) this.$countMessage = $module.querySelector('[id=' + this.$textarea.id + '-info]') } CharacterCount.prototype.defaults = { @@ -17,7 +18,9 @@ CharacterCount.prototype.init = function () { // Check for module var $module = this.$module var $textarea = this.$textarea - if (!$textarea) { + var $countMessage = this.$countMessage + + if (!$textarea || !$countMessage) { return } @@ -132,7 +135,7 @@ CharacterCount.prototype.checkIfValueChanged = function () { CharacterCount.prototype.updateCountMessage = function () { var countElement = this.$textarea var options = this.options - var countMessage = this.countMessage + var countMessage = this.$countMessage // Determine the remaining number of characters/words var currentLength = this.count(countElement.value)