Skip to content

Commit

Permalink
Make count message required
Browse files Browse the repository at this point in the history
The count message always exists (since
7b534bf). 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
  }
```
  • Loading branch information
hannalaakso committed Sep 26, 2019
1 parent f32909d commit 3b52b27
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/govuk/components/character-count/character-count.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 3b52b27

Please sign in to comment.