Sunday, May 19, 2024
140
rated 0 times [  146] [ 6]  / answers: 1 / hits: 36950  / 9 Years ago, thu, november 26, 2015, 12:00:00

I've seen a lot examples of Select2 option tags set with data- attributes and I would like to do it.



I'm using ajax to get the data. I get the ID and the TEXT needed to build the select.




But how can I add more attributes to it?




I just didn't find the way to add them.



$(element).select2({
placeholder: 'Select one...',
width: '100%',
minimumInputLength: 2,
ajax: {
url: '/my/url',
dataType: 'json',
data: function(params) {
return {
q: params.term,
page: params.page
};
},
processResults: function(data, page) {
console.log(data);
return {
results: data
};
},
cache: true
}
});

More From » jquery-select2

 Answers
140

This solution applies to Select2 versions 4.0 or higher.


Assuming the attributes your talking about are loaded in the array you are returning in processResults. For example, if you are selecting a record like ('id':1,'text':'some-text','custom_attribute':'hello world')


Then on a change event you can do:


data=$("#selector").select2('data')[0];
console.log(data.custom_attribute);//displays hello world

Hope it helps..


[#64261] Tuesday, November 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopher

Total Points: 58
Total Questions: 103
Total Answers: 102

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;