sukesh
sukesh

Reputation: 2437

select2 - do not scroll on selection

I have a select2 dropdown, that I would like to keep open so that user can multiselect.

The problem is, when user selects a menu item that is somewhere in the bottom, the item is selected, but the scroll position moves away.

$('#example').select2({
    placeholder: 'Select a month',
    closeOnSelect:false
});

The list is big and user would search for a keyword. User should be able to select all the items containing the keyword. But now, when one item is selected, the scroll moves to the first position.

https://jsfiddle.net/3x9Lh5kt/

For e.g., try selecting December in the list, the scroll moves a little above, whereas I would like it to stay at the same position.

What should be done to achieve that.

Upvotes: 3

Views: 3413

Answers (1)

User863
User863

Reputation: 20039

A solution using select2:selecting event

$('#example').select2({
  placeholder: 'Select a month'
}).on('select2:selecting', function(e) {
  var cur = e.params.args.data.id;
  var old = (e.target.value == '') ? [cur] : $(e.target).val().concat([cur]);
  $(e.target).val(old).trigger('change');
  $(e.params.args.originalEvent.currentTarget).attr('aria-selected', 'true');
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>

<select id="example" multiple="multiple" style="width: 300px">
  <option value="JAN">January</option>
  <option value="FEB">February</option>
  <option value="MAR">March</option>
  <option value="APR">April</option>
  <option value="MAY">May</option>
  <option value="JUN">June</option>
  <option value="JUL">July</option>
  <option value="AUG">August</option>
  <option value="SEP">September</option>
  <option value="OCT">October</option>
  <option value="NOV">November</option>
  <option value="DEC">December</option>
</select>

FYI multiple issue already available about this 4417, 5022 on github

Upvotes: 7

Related Questions