I'm using Select2 with ajax. Everything works fine, when the user click on the item they want, I use the on(change) function as specified by the documentation for doing some stuff.
$("#e6").on("change", function(e) {
$('input#Destination').val(e.val);
});
});
The return value (e.val) is the data.id value from the ajax call, but my data object has "name", "id" and "type".
I can add code to dataFormatSelection() but this doesn't sound logic and is confusing.
function dataFormatSelection(data) {
console.log(data.name + "|" data.id + "|" + data.type);
return data.name;
}
How can I access the whole data object (instead of just data.id) at the on("change".. event?
$("#e6").on('change', function(e) {
// Access to full data
console.log($(this).select2('data'));
});
According to Select2 docs change event should have 3 properties: The event object contains the following custom properties:
There is even example:
$("#e11").select2({
placeholder: "Select value ...",
allowClear: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
$("#e11_2").select2({
placeholder: "Select value ...",
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
$("#e11").on("change", function(e) {
console.log(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
}).on("open", function() {
console.log("open");
});
$("#e11_2").on("change", function(e) {
console.log(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
}).on("open", function() {
console.log("open");
});
But I noticed that added
and removed
properties are only present when multiple: true
is on. I don't know if this is by design or is it bug. I am going to report it anyway, because having the selected element available on change is definitely something needed.
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