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
2 Answers
Reset to default 6I 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744271112a4566106.html
评论列表(0条)