Attach click-event to element in .select2-result

Because Select2 lib prevent any click events on popover list you can't bind events to .info directly. But you can redefine onSelect method and place there any code you want.

See example: http://jsfiddle.net/f8q2by55/

Update for multiple selects: http://jsfiddle.net/6jaodjzq/


This is similar in concept to netme's but the select2 event is wrong(maybe version difference), and you need to use stopPropagation to prevent item from being selected:

http://jsfiddle.net/ZhfMg/

$('#mySelect2').on('select2-open', function() { 
    $('.select2-results .info').on('mouseup', function(e) { 
        e.stopPropagation();
        console.log('clicked');
    }); 
});

If used with x-editable. What this does is when the x-editable goes into edit mode(shown event), that's when a select2 exists and you can wire to it's open function.

$('#myXEditable').on('shown', function () {
    $(this).data('editable').input.$input.on('select2-open', function() { 
        $('.select2-results .info').on('mouseup', function(e) { 
            e.stopPropagation();
            console.log('clicked');
        }); 
    });
});

For versions of Select2 before 4.0.0 (so 3.5.x and below), you should refer to this answer about binding to onSelect.

In newer versions of Select2, events are no longer killed within the results so you can just bind to the mouseup/mousedown events like you normally would. You should avoid binding to the click event because by default browsers will not trigger it.

$(".select2").select2({
  templateResult: function (data) {
    if (data.id == null) {
      return data.text;
    }
    
    var $option = $("<spam></span>");
    var $preview = $("<a target='_blank'> (preview)</a>");
    $preview.prop("href", data.id);
    $preview.on('mouseup', function (evt) {
      // Select2 will remove the dropdown on `mouseup`, which will prevent any `click` events from being triggered
      // So we need to block the propagation of the `mouseup` event
      evt.stopPropagation();
    });
    
    $preview.on('click', function (evt) {
      console.log('the link was clicked');
    });
    
    $option.text(data.text);
    $option.append($preview);
    
    return $option;
  }
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>

<select class="select2" style="width: 200px;">
  <option value="https://google.com">Google</option>
  <option value="https://mail.google.com">GMail</option>
</select>

In this example we stop the propagation of the mouseup event so the browser will trigger the click event. If you are not working with actual links, but instead need to just catch a click event, you should just hook into the mouseup event.