4

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?

aynber
  • 22,380
  • 8
  • 50
  • 63
user1782730
  • 61
  • 1
  • 5
  • 1
    http://stackoverflow.com/questions/1280499/jquery-set-select-index and this http://stackoverflow.com/questions/7445492/how-to-reset-select-box-using-jquery – riti Oct 29 '12 at 11:30
  • I think this is browser-dependent, i.e. the browser decides at which scroll level to show the select box dropdown – redShadow Oct 29 '12 at 11:30
  • Is this a select element with multiple set to true? – epascarello Oct 29 '12 at 11:34

2 Answers2

1

Try this:

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

If this is what you mean?

Rick Kuipers
  • 6,616
  • 2
  • 17
  • 37
  • The poster does not want to move the actual selected option, just wants the scroll to be different. This will screw up the OP's order. – epascarello Oct 29 '12 at 11:40
  • "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?" Its an ambiguous question for sure. – A. Wolff Oct 29 '12 at 11:42
1

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

epascarello
  • 204,599
  • 20
  • 195
  • 236