Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Make <select onchange> or <option onclick> keyboard-accessible

Similar questions have been asked before, but I'm looking for the "opposite" solution than all the others ;-)

I need a JavaScript event that fires when a user decides for an option in a select field.

What do I mean by decide:

  • Mouse: Click to expand the select, then click to select any option.
  • Keyboard: Either:
    • Press the UP/DOWN keys to "scroll" through the options (without expanding the select), then press ENTER/TAB to select. Or:
    • Press ALT+DOWN to expand the select, then use the UP/DOWN keys to scroll through the options, and finally press ENTER/TAB to select.

Non-perfect solutions I've found so far:

  • onclick on each option: Firefox & Internet Explorer: Works for mouse, but not for keyboard. Chrome: Doesn't work at all.
  • onchange on the select: Firefox: Works as expected. Chrome & Internet Explorer: Fires too early when using just the UP/DOWN keys (without expanding the select): In the users' mind, they are just scrolling through the available options, not actually selecting anything yet.
    Albeit being popular, this approach violates WCAG: http://www.w3.org/TR/2012/NOTE-UNDERSTANDING-WCAG20-20120103/consistent-behavior-unpredictable-change.html
  • onblur on the select: Firefox & Chrome & Internet Explorer: Fires too late, only when actually leaving the select.
  • onkeydown on the select, plus evaluating the keyCode: Looks like a hassle to me, cause there might be (or turn out) other ways to confirm something than pressing the ENTER key (maybe on mobile devices).

The only solution I've found, having perfect accessibility, is ugly:

  • Having an explicit submit button and binding the event to this.

So (finally) my question is: Do you know any other way to achieve this without the submit button?

like image 845
Thomas Landauer Avatar asked Oct 14 '25 19:10

Thomas Landauer


1 Answers

You could use the onInput event:

The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.

Right now, Firefox doesn’t support the event on <select> elements, but since onChange works like you want in Firefox, you can pick and choose. (You want an onChange listener for backwards compatibility, anyway.)

like image 88
Tigt Avatar answered Oct 17 '25 08:10

Tigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!