Skip to content

Instantly share code, notes, and snippets.

@mrwweb
Created October 8, 2024 17:35
Show Gist options
  • Save mrwweb/0fd0fc72fc625e8bdbeaac4433b45ebc to your computer and use it in GitHub Desktop.
Save mrwweb/0fd0fc72fc625e8bdbeaac4433b45ebc to your computer and use it in GitHub Desktop.
Advanced Custom Fields Front-end Form Accessibility Fixes
/**
* Accessibility fixes for frontend Advanced Custom Fields forms
* v1.0.0
* Mark Root-Wiley, MRW Web Design (https://MRWweb.com)
*
* Fixes 3 issues:
*
* 1. Replace required asterisk with spelled-out label
* 2. Explicitly associate checkbox labels with their inputs using a for and id attribute
* 3. Use fieldset and legend to wrap checkbox and group fields
*
* I wrote this for my own needs. In the future, I'd want to add further support for checkboxes and radios (at least) in fix #3
* Ideally, these changes would be made via PHP, but I couldn't find a great filter to do that with.
* Feedback and suggestions greatly appreciated.
*/
'use strict';
const labels = document.querySelectorAll('.acf-label label');
const checkboxLabels = document.querySelectorAll('.acf-checkbox-list label');
const groupingFields = document.querySelectorAll(
'.acf-field-taxonomy, .acf-field-group'
);
/* Replace "*" with a "Required" label */
if (labels) {
labels.forEach((label) => {
const labelText = label.innerText;
label.innerHTML = labelText.replace(
'*',
'<span class="required">(Required)</span>'
);
});
}
/* Explicitly set for/id on checkbox labels */
if (checkboxLabels) {
checkboxLabels.forEach((label) => {
const input = label.querySelector('input[type="checkbox"]');
const checkboxId = 'checkbox-' + input.value;
input.id = checkboxId;
label.setAttribute('for', checkboxId);
});
}
/* Use fieldset/legend for Checkboxes, Taxonomy, Groups, etc. */
if (groupingFields) {
groupingFields.forEach((field) => {
const firstLabel = field.querySelector('.acf-label label');
const fieldset = document.createElement('fieldset');
firstLabel.remove();
fieldset.innerHTML =
'<legend>' + firstLabel.innerHTML + '</legend>' + field.innerHTML;
field.innerHTML = fieldset.outerHTML;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment