Auto Add Accessible Labels to Forms with JavaScript

We all know there are some shit plugins and themes and builders out there that doesnt add labels or its not user friendly to setup the labels on them so I decided to code this for those edge cases. Solving label issue without opening the ancient setups….

This script automatically adds accessible labels to all form fields (except buttons & checkboxes) if they don’t already have one. The label uses the placeholder, option text, or name as label text. It improves form accessibility for users and screen readers

// change with your #id or .class of your form
var formSelector = "form";

document.querySelectorAll(formSelector).forEach(function(form) {
    var inputs = form.querySelectorAll('input, textarea, select');
    inputs.forEach(function(input) {
        // Skip if already labeled
        if (input.previousElementSibling && input.previousElementSibling.tagName === 'LABEL') return;

        // Skip buttons and checkboxes
        if (
            input.type === 'button' ||
            input.type === 'submit' ||
            input.type === 'reset' ||
            input.type === 'checkbox'
        ) return;

        var labelText = '';

        if (input.placeholder && input.placeholder.trim().length > 0) {
            labelText = input.placeholder.trim();
        } else if (input.tagName === 'SELECT') {
            var firstOption = input.querySelector('option');
            if (firstOption) labelText = firstOption.textContent.trim();
        } else if (input.name) {
            labelText = input.name;
        } else {
            labelText = 'Input';
        }

        // Create and style label
        var label = document.createElement('label');
        label.textContent = labelText;
        label.className = 'accessible-label'; // Updated class

        // Generate unique id if missing, to associate label
        if (!input.id) {
            input.id = 'input-' + Math.random().toString(36).substr(2, 9);
        }
        label.setAttribute('for', input.id);

        input.parentNode.insertBefore(label, input);
    });
});

All form fields matched by input, textarea, select except those explicitly skipped will get labels. In practice, that means labels are generated for:

  • Input types:
    text, password, email, url, tel, search, number, date/datetime-local/month/week/time, color, range, file, radio, hidden, etc.
  • Other elements:
    <textarea> and <select>

Skipped (no labels added):

  • <input type="button">
  • <input type="submit">
  • <input type="reset">
  • <input type="checkbox">