Mattias Rasmusson
Mattias Rasmusson

Reputation: 120

Get/set value of clicked choice in Select2 multiple

I am using Select2 as multiselect on an input field. I am trying to find out which choice is being clicked, but if I look at the event thrown when clicking a choice ("choice-selected") all I can find is event.target.value which is the data array with all selected options (choices). Basically I want to access the clicked value so I can let the user edit a custom attribute in that specific choice. How could I go about doing that?

JSFiddle of the problem: http://jsfiddle.net/JtTTF/

$(test).bind("choice-selected", function(e) {
 alert(e.target.value);
    // this is where i would like to access the clicked choice id so i can edit the custom data attribute "reason"
});

Upvotes: 1

Views: 7495

Answers (2)

David L. Walsh
David L. Walsh

Reputation: 24815

I ran into this as well. After examining the select2.js source code, I found that the choice-selected event passes a second parameter: the dom element you clicked.

This dom element contains a data object with key "select2-data".

Your code might look something like this:

$(test).on("choice-selected", function(e, choice) {
    var data = $(choice).data('select2-data');
    alert(data.reason ? 'Reason: ' + data.reason : 'No Reason');
});

I've updated your jsfiddle accordingly.

Upvotes: 6

Arun P Johny
Arun P Johny

Reputation: 388416

Try

var selected = {};
$(test).change(function () {
    var selections = $(this).select2('data');
    $.each(selections, function (idx, obj) {
        if (!selected[obj.id]) {
            selected[obj.id] = obj;
            $('#selectedText').text(JSON.stringify(obj));
            return false;
        }
    })
});

Demo: Fiddle

Note: Haven't seen whether there is inbuilt support to do this, but a custom implementation

Upvotes: 0

Related Questions