user1896653
user1896653

Reputation: 3327

How to add HTML content at select2 dropdown box

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'}]
});

});

Upvotes: 12

Views: 14796

Answers (1)

Luís Cruz
Luís Cruz

Reputation: 14970

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.

Upvotes: 14

Related Questions