Search code examples
javascriptjqueryjquery-select2

How to place a button into a select2 result item and handle its click?


I'm trying to place a button into select2 result items (for allowing the user to remove items). I managed to place the buttons, but I didn't manage to handle their click event yet. Somehow the event doesn't get raised. I think it's something like select2 is closing the dropdown before my button's click event would raise, but cannot figure out how I could make it work.

Here is the snippet what I have now.

...    
formatResult: function (item) {
    return item.text + "<button class='btn btn-xs btn-default pull-right select2-result-button' data-id='" + item.id + "'>&times;</button>";
}
...
$(document).on("click", ".select2-result-button", function (e) {
    alert("clicked: " + $(this).data("id"));
    e.preventDefault();
    e.stopPropagation();
    return false;
});

Here is a demo fiddle. I've also tried the mousedown event without success.


Solution

  • You should have a look to this answer : stackoverflow.com/a/15637696/1127669 : the select2 library prevents any click event on the popover list.

    But you can redefine the onSelect event like this : jsfiddle.net/qouo8uog/33.

    s2list.onSelect = (function (fn) {
        return function (data, options) {
            var target;
    
            if (options != null) {
                target = $(options.target);
            }
    
            // In case where the target is your own button, handle it
            if (target && target.hasClass('select2-result-button')) {
                alert("clicked: " + $(target).data("id"));
            } else {
                return fn.apply(this, arguments);
            }
        }
    })(s2list.onSelect);