From 5773cde469bebf06ac578d08c94f33bb3af9210f Mon Sep 17 00:00:00 2001 From: Antti Hukkanen Date: Fri, 4 Mar 2022 16:58:49 +0200 Subject: [PATCH] fix(abide): add aria-describedby to the input only if error is visible --- js/foundation.abide.js | 36 ++++++++++++++++++-------- test/javascript/components/abide.js | 40 +++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/js/foundation.abide.js b/js/foundation.abide.js index 4e740c918..cd1aca349 100644 --- a/js/foundation.abide.js +++ b/js/foundation.abide.js @@ -282,6 +282,10 @@ class Abide extends Plugin { 'data-invalid': '', 'aria-invalid': true }); + + if ($formError.filter(':visible').length) { + this.addA11yErrorDescribe($el, $formError); + } } /** @@ -292,19 +296,11 @@ class Abide extends Plugin { addA11yAttributes($el) { let $errors = this.findFormError($el); let $labels = $errors.filter('label'); - let $error = $errors.first(); if (!$errors.length) return; - // Set [aria-describedby] on the input toward the first form error if it is not set - if (typeof $el.attr('aria-describedby') === 'undefined') { - // Get the first error ID or create one - let errorId = $error.attr('id'); - if (typeof errorId === 'undefined') { - errorId = GetYoDigits(6, 'abide-error'); - $error.attr('id', errorId); - } - - $el.attr('aria-describedby', errorId); + let $error = $errors.filter(':visible').first(); + if ($error.length) { + this.addA11yErrorDescribe($el, $error); } if ($labels.filter('[for]').length < $labels.length) { @@ -331,6 +327,20 @@ class Abide extends Plugin { }).end(); } + addA11yErrorDescribe($el, $error) { + if (typeof $el.attr('aria-describedby') !== 'undefined') return; + + // Set [aria-describedby] on the input toward the first form error if it is not set + // Get the first error ID or create one + let errorId = $error.attr('id'); + if (typeof errorId === 'undefined') { + errorId = GetYoDigits(6, 'abide-error'); + $error.attr('id', errorId); + } + + $el.attr('aria-describedby', errorId).data('abide-describedby', true); + } + /** * Adds [aria-live] attribute to the given global form error $el. * @param {Object} $el - jQuery object to add the attribute to @@ -419,6 +429,10 @@ class Abide extends Plugin { 'data-invalid': null, 'aria-invalid': null }); + + if ($el.data('abide-describedby')) { + $el.removeAttr('aria-describedby').removeData('abide-describedby'); + } } /** diff --git a/test/javascript/components/abide.js b/test/javascript/components/abide.js index 0b61460fe..19ea148db 100644 --- a/test/javascript/components/abide.js +++ b/test/javascript/components/abide.js @@ -133,7 +133,7 @@ describe('Abide', function() { $html = $(`
- +
`).appendTo('body'); plugin = new Foundation.Abide($html, {}); @@ -143,11 +143,47 @@ describe('Abide', function() { $html.find('label.form-error').should.have.attr('for', 'test-input'); }); + it('does not add [aria-describedby] to the field if the form error is hidden', function() { + $html = $(` +
+