22
Views
2
Comments
Solved
[Dynamic Radio and Button Group] How to change value with arrow keys? (ARIA Authoring Practices Guide (APG))
dynamic-radio-and-button-group
Reactive icon
Forge asset by darwinLabs Dev Team
Application Type
Reactive

How to change radio group value with arrow keys?

Radio Group Pattern | APG | WAI | W3C

2024-10-03 06-30-47
Bharathiraja Loganathan
Solution

1. Assign TabIndex and Key Event Handler

For each radio/button option:

  • Set TabIndex = If(CurrentSelectedOption = ThisOption, 0, -1)

  • Set a KeyDown or KeyUp event on the widget.

2. Handle Arrow Keys (Left/Right or Up/Down)

In the OnKeyDown handler (or JavaScript if needed), check for:

  • ArrowRight or ArrowDown → move to next option

  • ArrowLeft or ArrowUp → move to previous option

3. Change Selected Option and Focus

In the event logic:

  • Set the new selected index/option.

  • Use Focus action (JavaScript) to move focus to the correct element.



    use javascript 

    document.querySelectorAll('.custom-radio-button').forEach((btn, index, btns) => {

      btn.addEventListener('keydown', function(e) {

        let nextIndex = index;

        if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {

          nextIndex = (index + 1) % btns.length;

        } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {

          nextIndex = (index - 1 + btns.length) % btns.length;

        } else {

          return;

        }

        e.preventDefault();

        btns[nextIndex].focus();

        btns[nextIndex].click(); // trigger selection

      });

    });

2018-10-02 08-27-21
RLinter

Thank you very much for you idea / answer.

Have / had problems to follow instructions how to implement.

Not working 100% well. But is perhaps my fault that i didn't understand instructions completele.

For production use i did make solution where i build complete radio-group myself with javascript and their the tab behavior works without code.

Would great developer of component find solution that it works out of box.

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.