Otaqui.com Blog

Fix The “For Attribute Resets Focus on Select Tag” Bug In Internet Explorer using Prototype

Browser sniffing is bad, or so the logic goes.

There are occasions though where it makes perfect sense – for example where you are fixing a known bug in a specific version of a browser. A good example is the bug in IE 6 that resets the selected index of a Select tag that has a label and the for attribute. This bug doesn’t affect IE 7 or 8, or any other browser, but does make for a bad user experience if you are doing the right thing and including labels for your select tags.

Microsoft has published some javascript to fix this and I adapted their code to work with with the Prototype Javascript Library .

This fix will look for all select tags on the page (you could adapt it to only look for those with the “for” attribute but I have a sneaking suspicion that if anything that would in fact be a bit slower) and observe the onfocusin and onfocus events as suggested in the knowledge base article.

// Select with 'for' attribute fix for IE
Event.observe(window,'load',function() {
	if ( !Prototype.Browser.IE || !(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6) ) return;
	$$('select').each(function(eSelect) {
		eSelect.observe('focusin',function(e) {
			try {
				var eSrc = window.event.srcElement;
				if ( eSrc ) eSrc.tmpIndex = eSrc.selectedIndex;
			} catch(e) {}
		});
		eSelect.observe('focus',function(e) {
			try {
				var eSrc = window.event.srcElement;
				if ( eSrc ) eSrc.selectedIndex = eSrc.tmpIndex;
			} catch(e) {}
		})
	});
});