user1782730
user1782730

Reputation: 61

Make the selected option in a Select box always appear at the top

The select box I am using has 4 top level options, each with a list of options below it. The selected one is appearing at the bottom of the list meaning that the user still has to scroll up to see the sub-options.

My question is, how can I make the 'selected' option be at the top? i.e. so that the entire select box has scrolled so that it appears at the top?

Upvotes: 4

Views: 2665

Answers (2)

epascarello
epascarello

Reputation: 207557

What you can do is find the selected index, select an option near the end and reselect the selected item and the item will appear at the top of the list. It is hacky, but works. This is also works only for single select, you would have to reselect all options if it is multiple.

var sel = ​document.getElementById("yourSelect");
var optsLen = sel.options.length;
var selIndex = sel.selectedIndex;
var size = sel.size;
if (selIndex>=size) {
    var newIndex = selIndex+size+1;
    if (newIndex>optsLen) {
        newIndex = optsLen;
    }
    sel.selectedIndex = newIndex;
    setTimeout(function(){sel.selectedIndex = selIndex},1); //slight delay so line above runs
}

JSFiddle

Upvotes: 1

Rick Kuipers
Rick Kuipers

Reputation: 6607

Try this:

$('select option:selected').before($('select option:first'));

If this is what you mean?

Upvotes: 1

Related Questions