When there are a large number of items selected in a Select2 control and it’s long enough to run off the bottom of the screen, a very unwanted result occurs. When trying to click the “x” to remove an item, the select search is given the focus, and this causes the page to jump to the bottom. It also does NOT remove the item clicked. I’ve found a plugin to cause the search results to always open upwards (if desired), so that part won’t be an issue, but I can’t seem to get it to STOP setting the focus to the bottom of the control. First, I’d like to know if there’s any way to stop the search element from being set with the focus when merely clicking the “x” to remove an item. There’s no reason whatsoever to open up the dropdown just to remove an item. Aside from that, I’d like to be able to move the search element to the top of the generated “ul” list. This “li” is always at the end of all possible selections, with the classes “select2-search select2-search–inline”. I can use jQuery to find this element, but moving it does nothing, particularly because when selecting an item, it will simply re-generate at the bottom of the list again. It would be FAR better to have this option at the top than the bottom, but though I’ve searched for an hour, I haven’t found anything yet.
As a very ugly hack, since I couldn’t find anything that provided what I needed, I simply edited the select2 plugin itself, commenting out everywhere the focus was set. That’s what was causing the problems - jumping the screen and screwing up the removal of top items during the jump. I’d still like a better, more elegant solution… but this works for now.
To change such fundamental behavior of the Select2, you would have to supply your own implementation of the DropdownAdapter and perhaps the SelectionAdapter. You’ve essentially done the same thing by editing the Select2 source code, so I’d just go with that.
In case anyone else wants this behavior, one quick way is to edit the Search.prototype.update function, replacing the call to append the $searchContainer with “prepend”. For me, this was on line 2139 of the source code of version 4.0.10. I also found a plugin that allows a config option to force the “dropdown” to open from the top instead of the bottom, and together these did what I needed.