The following code works fine in most browsers but it won’t work in Internet Explorer CE Mobil and I can’t for the life of me figure out why.
function autofocus() {
var el = document.getElementById("autofocus");
if (el === null) {
return;
} else if (el.tagName.toUpperCase() == "SELECT") {
if (el.selectedIndex == -1) {
el.options[0].selected = true;
}
}
el.focus();
}
$(window).ready(function () {
autofocus();
});
It works perfectly in all the regular browsers I have tried but in Internet Explorer Mobile it seems to focus on the select list itself which means it’s not possible to navigate the various options without clicking one. Maybe if I click one of the options instead?. See http://jsfiddle.net/mhenrixon/sbwCv/19/ for an example of what is not working.
EDIT: It does not have to do with the selectedIndex per se since most of the time there will be a selectedIndex like 15, 5, 27 or whatever. Just not -1.
On my Samsung Saga, I’m running:
Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 7.11) VZW:SCH-i770 PPC 320×320
and the problem on this browser is the jQuery
readyfunction.If instead you use
<body onload="autofocus()">the<select>will have its first option selected. And that option is indeed focused; if I use the optical mouse, I can right-arrow to a different option and space-bar to select it.So here’s the test case I’ve ended up with:
And of course it works on desktop browsers as well.