Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 222
Zoltán Tamási Avatar asked Sep 15 '14 12:09

Zoltán Tamási


People also ask

How do I assign a value to Select2?

To dynamically set the "selected" value of a Select2 component: $('#inputID'). select2('data', {id: 100, a_key: 'Lorem Ipsum'}); Where the second parameter is an object with expected values.

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

What triggers an event Choose 2?

Select2 will trigger a few different events when different actions are taken using the component, allowing you to add custom hooks and perform actions. You may also manually trigger these events on a Select2 control using . trigger .

How do you add select all in Select2?

Add Select All Option to jQuery Select2: First create the markup for the multi-value select box and a check box for selecting all option. Now add this java script to the page. The above script will be executed by onclick() event of the check box.


1 Answers

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);
like image 107
Samuel Caillerie Avatar answered Sep 17 '22 20:09

Samuel Caillerie