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.
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.
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).
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With