How to place a button in a select2 result element and handle its click?

I am trying to put a button in select2 result items (to allow the user to delete items). I managed to place the buttons, but I still could not handle their click event. Somehow the event does not rise. I think something like select2 closes the dropdown menu before my button click event goes up, but cannot figure out how I can make it work.

Here is a snippet that 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 the fiddle demo. I also tried the mousedown event without success.

+7
javascript jquery jquery-select2
source share
2 answers

You should take a look at this answer: https://stackoverflow.com/a/2129608/212632 : select2 prevents any click event in the popover list.

But you can override 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); 
+2
source share

At the end of the day, I decided to fix select2 source code instead of hacking options. It would probably be worthwhile for the github project to attract a request, but at the moment I don’t have time to prepare it.

In both implementations of onSelect (one and several) I put this code in front.

 onSelect: function (data, options) { // @@ implement a way to be able to place buttons in results // this will check if there is an event target (in case when selection is invoked by mouse/touch), and if the target is a result button, trigger the result button event on the element, and skip default selecting behaviour if (options && options.target && $(options.target).hasClass('select2-result-button')) { var evt = $.Event("select2-result-button-click", { choice: data, button: options.target }); this.opts.element.trigger(evt); return; } ... } 
0
source share

All Articles