Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get select2 dropdown to scroll to selection when initially opened

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.

like image 563
Quasipickle Avatar asked Dec 13 '25 09:12

Quasipickle


1 Answers

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);
    })
like image 115
jQuerybeast Avatar answered Dec 15 '25 03:12

jQuerybeast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!