Checkbox Aria TagHelper
Source: Dev.to
Introduction
Learn how to initialize all checkbox inputs that reside in an ASP.NET Core page using a custom TagHelper.
The TagHelper evaluates the checked attribute value on page load and adds/sets the aria-checked attribute. This is important for screen readers to assist people with limited or no vision.
How to use
-
Create the TagHelper
In an ASP.NET Core project, create a folder namedTagHelpersand add the following class:using Microsoft.AspNetCore.Razor.TagHelpers; [HtmlTargetElement("input", Attributes = "asp-for")] public class CheckboxAriaTagHelper : TagHelper { public override void Process(TagHelperContext context, TagHelperOutput output) { if (!output.Attributes.TryGetAttribute("type", out var type) || type.Value.ToString() != "checkbox") return; var isChecked = output.Attributes.TryGetAttribute("checked", out var chk); output.Attributes.SetAttribute("aria-checked", isChecked); } } -
Register the TagHelper
Add the following line toPages/_ViewImports.cshtml. ReplaceCheckedListBoxwith your project’s root namespace.@addTagHelper *, CheckedListBox -
Add checkbox inputs to a page
The example below shows how to render a list of checkboxes bound to a model (CheckModels). The TagHelper runs on each<input>of typecheckbox.@for (var index = 0; index @Model.CheckModels[index].Name } -
Add JavaScript to keep
aria-checkedin sync
Place the script in aScriptssection (or any appropriate location) so it runs after the DOM is loaded.@section Scripts { document.addEventListener("DOMContentLoaded", () => { document.querySelectorAll("input.js-aria-checkbox[type='checkbox']").forEach(cb => { // Update aria-checked whenever the checkbox changes cb.addEventListener("change", function () { this.setAttribute("aria-checked", this.checked ? "true" : "false"); }); }); }); }
Testing
- Run the page in a browser.
- Open Developer Tools.
- Select a checkbox input and toggle its state.
- Observe that the
aria-checkedattribute updates to"true"or"false"accordingly.
The TagHelper simplifies setting the aria-checked attribute, providing a better experience for users with vision disabilities.