Reputation: 3
When am skipping input fields am showing a error message under the input field. Also to read the error message by screen readers am using role="alert"
and also tried using aria-live="assertive"
(without role). In both the case screen readers are reading the error message but not immediate. It reads the element label first and then the error message of previous element.
Code Snippet
<form>
<section>
<input type="text" name="fname" placeholder="fname" class="eleField" aria-invalid="false" aria-required="true" required aria-label="First name"/>
<div class="inline-message" role="alert">
Enter fname
</div>
</section>
<section>
<input type="text" name="lname" placeholder="lname"
class="eleField" aria-invalid="false" aria-required="true" required aria-label="Last name"/>
<div class="inline-message" role="alert">
Enter Lname
</div>
</section>
</form>
$(document).on('blur', '.eleField', function() {
if ($(this).val() === '') {
$(this).attr('aria-invalid', true);
$(this).next('.inline-message').show();
} else {
$(this).attr('aria-invalid', false);
$(this).next('.inline-message').hide();
}
});
Upvotes: 0
Views: 3298
Reputation: 526
You may want to consider using HTML5 Validation instead of using custom JavaScript. Because they are native to the browser, the support with assistive technologies is a bit better.
However, if you do want display custom alerts, you don't need to add role=alert or aria-live attributes. "aria-live" is just a suggestion to the screen reader, and it is sometimes ignored. A better practice is to:
Associate the error message to the input box
Add a unique ID to the error message container. Then add the aria-describedby attribute to the input element, with a value of the error message's ID.
<input type="text" name="fname" placeholder="fname" class="eleField" aria-describedby="fname-error"/>
<div id="fname-error" class="inline-message">
Enter fname
</div>
Focus the first input element with an error message on submit.
You've already marked the invalid fields with "aria-invalid=true". The below jQuery focuses the first element with that attribute. When the field receives focus, it will also read the error message because of the aria-describedby.
$("form").submit(function(){
$("form *[aria-invalid=true]").first().focus();
})
Don't forget to also add labels elements for all your inputs fields. :)
Codepen: https://codepen.io/camtin/pen/drvjjb
Upvotes: 1