How to change radio group value with arrow keys?
Radio Group Pattern | APG | WAI | W3C
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
});
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.