I\'m looking for a way to attach a click-event to a select2-result-item. I\'ve gone ahead and formatted both result and selection via
function format(state)
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 = $("");
var $preview = $(" (preview)");
$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;
}
});
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.