How to add HTML content at select2 dropdown box
Asked Answered
K

1

12

I've used Select2 plugin for tag input. Here is the fiddle of my basic work. I need showing "used number" of each options/tags at dropdown box like this way:

I've created a class for that number in my CSS (.used-number). But, I don't understand how can I add that number for each options at my HTML file. Is there a way to add those something like this(or any other way):

$(".tag").select2({
     data:[{tag: 'red',text:'3',className: 'used-number'},{tag: 'green',text:'12',className: 'used-number'},{tag: 'blue',text:'5', className: 'used-number'},{tag: 'black',text:'7'}]
});

});

Kial answered 12/8, 2014 at 14:30 Comment(0)
N
14

The tags array must contain objects with the keys id and text. You can add more keys if you need (for your case, I've added the key qt that represents the number).

To add HTML to the option you need to change the default formatResult function. With the following code, the numbers appear to the tags that exist (that is, the tags passed to the select2). For the options created on the fly, the number will not appear.

$(".tag").select2({
    tags:[
        {id: "red", text: "red", qt: 3},
        {id: "green", text: "green", qt: 12},
        {id: "blue", text: "blue", qt: 5},
        {id: "black", text: "black", qt: 7}
    ],
    formatResult: function(result) {
        if (result.qt === undefined) {
            return result.text;
        }

        return result.text
            + "<span class='used-number'>"
            + result.qt
            + "</span>";
    }
});

See the forked fiddle.

Nonproductive answered 12/8, 2014 at 21:49 Comment(4)
This functionality works. But, problem is at my fiddle, you'll look that you can input your own tag. But, at your fiddle, free-hand tag can't be makeKial
This will be resolved if I use tags instead of data. But, at that time, suggestion box's text showed "undefined" in place of number for random text. I want, for random text nothing will be showed in place of number. jsfiddle.net/learner73/fc56928s/2Kial
Sorry, I didn't understand that from your question. I have edited my answer and the fiddle in order to fit your needs.Modernistic
Please note that in version 4 the method name formatResult has been renamed to templateResult. select2.github.io/announcements-4.0.htmlDereism

© 2022 - 2024 — McMap. All rights reserved.