Accessible JavaScript onchange select menu

Update: This script is from 2006. I’m sure there must be other better solutions by now.

Selectboxes that react immediatly when a selection is done, is more userfriendly when using the mouse (reacting imideately instead of forcing the user to click on a “Go” button), but unaccessible when only using the keyboard, with for example the IE browser (see OnChange Event Accessibility Issues.)

This is a solution, suggested by Thomas Frank. It redefines the event handlers of the select box.

[Read more after the jump.]

Here is a live example. It’s appreciated if you test it and report any problems or anomalies either here as a comments or to tommy@heltenkelt.se.

<script type="text/javascript"> /* Nice select A select list that works without a submit button for also for keyboard users.

Works like this:
- If a select is clicked then we assume that the user is using a mouse and don’t wait for enter.
- Else we assume that the user is not using a mouse and wait for enter to get pressed…

©2006 Thomas Frank, Studentlitteratur

*/
niceSelect=function(){
var f=document.forms;
for (var i=0;i<f.length;i++){ // Walks all the forms in the document.
var e=f[i].elements;
for(var j=0;j<e.length;j++){ // Walks all the elements in the form.
if(e[j].type==“select-one”){ // Chooses elements that are select
// box (that does not allow multiple
// selections).
e[j].formnu=i;
// Here comes the “trick” of this
// script: it redefines the
// event handlers of the element.

e[j].onclick=function(){ // If the selection is made // with the mouse, the it // behaves like a normal selectbox // menu and submits). this.onchange=function(){ f[this.formnu].submit() } }; e[j].onblur=function(){ // This “disarms” the onblur function // so that it will not submit as soon // as the default option is deselected // (by moving down the select list with // the arrow key). this.onchange=function(){return true} }; e[j].onkeydown=function(e){ // When keys are pressed on the keyboard… if (e){theEvent = e} else {theEvent=event}; if (theEvent.keyCode==13){ // …only submit when ‘enter’ is pressed. if((this.onchange+"").indexOf(“submit”)<0){ f[this.formnu].submit() } } } } } }

}


This script can then be used by forms like this:

Test form for Accessible JavaScript onchange select menu


(In order to make the solution accessible also for users without javascript, the javascript call needs to be moved from the action attribute to a onsubmit event handler, and a <noscript><input type=“submit”></noscript> should be added. But right now I’m only interested in if this approach will work with all kinds of browsers.)

Other takes at the same problem

comments powered by Disqus