How to add HTML content at select2 dropdown box

前端 未结 1 1902
慢半拍i
慢半拍i 2021-02-13 20:34

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:

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 21:09

    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
                + ""
                + result.qt
                + "";
        }
    });
    

    See the forked fiddle.

    0 讨论(0)
提交回复
热议问题