Sunday 8 August 2010

Chrome may fire OnKeyUp event when you give focus to a SELECT box

Trying to create an select-as-you-type text box using Javascript, I wanted to open a SELECT box listing matches for text typed so far: no problem.

The challenge came when I wanted use of down-arrow from the text box to result in the first item in the select box being displayed and selected. In Chrome, setting the focus to the SELECT box was fine for an instant, but also resulted in the "onkeyup" event being fired and the focus moving away from the SELECT box. That isn't correct: onkeyup should only fire if the user has clicked on the SELECT box, and I had moved there programatically.

The solution was to use the onkeyup event to call a function that would specify thisObj.selectedIndex=0; - this brought focus back to the SELECT box. Of course, that then needed a boolean value setting in the onKeyDown so that Icould distinguish between normal and "phantom" keyup events.


... select id='monikerSelect' onkeyup='handleSelectKeyUp();'  ...


function handleSelectKeyUp(){
//CHROME triggers this immediately after passing focus.
    //We cannot stop it firing, so we need to try and make it put right what it mucks up

if (glob_selectDownHasBeenRun){
    //this is a keyup which follows a keydown: normal use
} else {
    //this is an orphan keyup that Chrome has invented for itself: THE PROBLEM CASE
    document.getElementById("monikerSelect").selectedIndex=0;
}
glob_selectDownHasBeenRun=false;
}

No comments: