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 + "'>×</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.
return false
is equivalent toe.preventDefault(); e.stopPropagation()
. – Deserte.preventDefault(); e.stopPropagation(); return false;
etc be on the<select>
element then instead of the button? You wan't to stop the drop down from closing down right? – Morganmorganaselect2
prevents any click event on the popover list. But you can redefine theonSelect
event like this : jsfiddle.net/qouo8uog/33. – Radioactive