haltersweb / Accessibility

Accessible solutions to web widgets and applications
http://haltersweb.github.io/Accessibility/
MIT License
125 stars 28 forks source link

Converted to vanilla JS #24

Open mra11yx opened 5 years ago

mra11yx commented 5 years ago

@haltersweb I converted this to vanilla JS, but wasn't sure how to actually submit a request properly. I need to get more familiar with using GitHub. Here's the updated code. Probably is kind of hacky, but it works.

Using [].slice.call on document.querySelectorAll for IE11 compatibility.

(function() {

/**
 * @author Adina Halter
 * Accessible Form Error Handling
 */

    'use strict';
    var $submitButton = [].slice.call(document.querySelectorAll('[type="submit"]')),
        $requiredFields = [].slice.call(document.querySelectorAll('[aria-required="true"]')),
        formErrors = {
            lastName: "You must enter your last name.",
            firstName: "You must enter your first name."
        };
    $requiredFields.forEach(function(el) {
        el.addEventListener('blur', function (evt) {
            var $this = evt.target,
                id = $this.id,
                $errMsg = document.getElementById(id + "Err");
            if ($this.value === "") {
                $errMsg.textContent = formErrors[id];
                $this.setAttribute('data-ok', 'false');
                $submitButton.forEach(function(submitEl) {
                    submitEl.setAttribute('aria-disabled', 'true');
                });
                return false;
            }

            $errMsg.textContent = "";

            $this.setAttribute('data-ok', 'true');
            if (document.querySelectorAll('[data-ok="true"]').length === 2) {
                $submitButton.forEach(function(submitEl) {
                    submitEl.setAttribute('aria-disabled', 'false');
                });

            }
        });
    });

    [].slice.call(document.querySelectorAll('[type="checkbox"]')).forEach(function(checkboxEl) {
        checkboxEl.addEventListener('change', function (evt) {
            if (evt.target.checked) {
                document.getElementById('catName').removeAttribute('disabled');
                return true;
            }
            document.getElementById('catName').setAttribute('disabled', 'disabled');
        });
    });

    $submitButton.forEach(function(submitEl) {
        submitEl.addEventListener('click', function (evt) {
            evt.preventDefault();
            if (evt.target.getAttribute('aria-disabled') === "true") {
                return false;
            }
            alert('Good Job filling out this form!');
        });
    });
}());
josiepizzo commented 5 years ago

Do you have the html & css that goes with this. Maybe demo on like JS fiddle?

haltersweb commented 5 years ago

Thank you @mra11yx !! Great work!! As you know I'm heads down with the rotation. I will give this some love later.