Select2 doesn’t scroll down automatically on selected option on opening

49 views Asked by At

When I select the option named "Item 6" (at the middle of the list) and re-open select2 element, it doesn't scroll down automatically on the selected option on opening but stays at the top.

Here is the recosntruction of the fully working example: jsfiddle

<div class="container body-content">
     <div class="form-group">
         <select class="js-example-basic-multiple form-control"></select>
     </div>
</div>
var data = [{"text":"Group 1","children":[{"id":"1","text":"Item 1"},{"id":"2","text":"Item 2"}]},{"text":"Group 2","children":[{"id":"3","text":"Item 3"},{"id":"4","text":"Item 4"}]},{"text":"Group 3","children":[{"id":"5","text":"Item 5"},{"id":"6","text":"Item 6"}]},{"text":"Group 4","children":[{"id":"7","text":"Item 7"},{"id":"8","text":"Item 8"}]},{"text":"Group 5","children":[{"id":"9","text":"Item 9"},{"id":"10","text":"Item 10"}]}];

var options = {
    data: data,
    placeholder: "Please select",
    multiple: true,
    allowClear: true,
    closeOnSelect: false,
    theme: "bootstrap"
};

$('.js-example-basic-multiple').select2(options);

// hide search field
$('.js-example-basic-multiple').on('select2:opening', function (e) {
    $('.select2-search__field').prop("readonly", true);
});

$('.js-example-basic-multiple').on('select2:selecting', function (e) {
  
    var selectedOption = e.params.args.data;    
    
    // disable options but selected
    $(this)
        .find('option')
        .each(function (i, option) {                        
            if ($(option).attr('value') != selectedOption.id)
                $(this).attr('disabled', true);                
        });
  
    // re-initialize select after disabling options
    $(this).select2({      
        placeholder: "Please select",
        multiple: true,
        allowClear: true,
        closeOnSelect: false,
        theme: "bootstrap"
    });
    
    // even select2 element open immediately, it doesn't scroll to the selected option
    //$(this).select2('open'); 
});

Investigating that ".select2-results__options" css setting of "max-height: 200px" can be where problem start? Because when set this to 500px and re-open select2, it scrolls down on the selected option as expected. Please see the images below.

"css class"

"max-height: 200px; definition"

Re-initializing select2 after disabling options causes something wrong.

Any help will be appreciated. Thanks.

(ps. Hiding search field or bootstrap css definitely not causing this issue.)

0

There are 0 answers