最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getset value of clicked choice in Select2 multiple - Stack Overflow

programmeradmin5浏览0评论

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: /

$(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"
});

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/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"
});
Share Improve this question edited Dec 18, 2013 at 0:31 Mattias Rasmusson asked Sep 29, 2013 at 1:21 Mattias RasmussonMattias Rasmusson 1201 silver badge15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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

发布评论

评论列表(0)

  1. 暂无评论