Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

javascript - Adding "data-" attributes with select2

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
     }
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...