3
votes

When I attach jquery select2 to a <select> that already has an option selected, the dropdown does not show the selected option. If I choose a new option, close the dropdown, then re-open it, the dropdown does show the option.

Example fiddle here: https://jsfiddle.net/9tf2nx8L/1/

Steps to reproduce:

  1. Notice "5" is selected in the markup
  2. Click the select2 box
  3. Notice how the list of options starts at the top
  4. Click another option.
  5. Click outside the dropdown, causing it to disappear
  6. Click the select2 box again
  7. Notice how the list of options has scrolled to have your newly selected option visible

I'm thinking this is a bug report, but wanted to sanity-check it with SO first.

2
Found the solution?jQuerybeast
@jQuerybeast Nope.Quasipickle

2 Answers

2
votes

There you go:

function dropscroll(){
        document.getElementById($(".select2-results__options").attr("id")).scrollTop = $(".select2-results__option[aria-selected=true]").outerHeight() * $(".select2-results__option[aria-selected=true]").index() - 100;
    }
    $(document).on("click",".select2-container", function(){
        setTimeout("dropscroll()",1);
    })
0
votes

You may have to do some overriding of some select2 core. The method that is invoked that scrolls to the currently selected item is the

ensureHighlightVisible()

It's located inside of the results module of select2. If you go down the route of overriding the core, you can hook into the 'results:all' event from select2 when you bind to the results module. Your code would look something like so:

[omitted code here]

    YourClassThatOverridesResults.prototype.bind = function (decorated, container, $container) {
                var self = this;
                decorated.call(this, container, $container);

                container.on('results:all', function (params) {
                    if (container.isOpen())
                    {
                        self.setClasses(params);
                        self.ensureHighlightVisible();
                    }
                });
    }
[omitted code here]

If this seems like a roundabout answer - it is. I don't know how deep down the rabbit hole you want to go, but I hope it can lead you in the right direction.