3

I'm using Select2 4.0 and want to be able to handle when users click on the currently selected option, however Select2 doesn't appear to expose the select2:selecting or select2:select events on this option.

In the below code snippet I've added logging for the select2:open, select2:selecting, select2:close and select2:select events:

$(function() {
  $('select').select2({ placeholder: '' });
  
  $('select').on('select2:open', function(elem) {
    $('<li>').text('Open').appendTo('ol');
  });
  
  $('select').on('select2:selecting', function(elem) {
    $('<li>').text('Selecting...').appendTo('ol');
  });
  
  $('select').on('select2:close', function(elem) {
    $('<li>').text('Close').appendTo('ol');
  });
  
  $('select').on('select2:select', function(elem) {
    $('<li>').text('Selected "' + elem.target.value + '"').appendTo('ol');
  });
});
select {
  width: 256px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css">

<select>
  <option></option>
  <option value="Foo">Foo</option>
  <option value="Bar">Bar</option>
</select>

<ol></ol>

If we select "Foo", then select "Bar", then select "Bar" again, we'll get the following output:

Example

Upon selecting "Bar" the second time (whilst it's already selected), the select2:selecting and select2:select events are not exposed. These events would otherwise fall in position 10 and 12, moving the select2:close event to position 11.

I'm not that interested in select2:selecting, but is there any way to get the select2:select event to fire when a user clicks the already-elected option?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Possible solution: http://stackoverflow.com/questions/16486281/always-trigger-change-event-for-select-even-if-the-select2-option-clicked-i. Not sure 100% sure if this is compatible with the version you're using though. – Rory McCrossan Jan 29 '16 at 11:29
  • @RoryMcCrossan I just tried the accepted solution on my local implementation and it doesn't appear to work on 4.0. I'm not sure if this is because the event names and data-attributes are different in 4.0 though. The other answer which triggers on `select2:close` won't really do the trick here as that'd cause the content to reload every even when the user makes no selection. – James Donnelly Jan 29 '16 at 11:32

0 Answers0