Styling individual select2 tags

浪子不回头ぞ 提交于 2019-12-23 03:53:16

问题


I'm trying to style individual select2 tags using Bootstrap's button styles (.btn-primary and .btn-danger) based on if the user created a tag (applying the red .btn-danger style) or if the user selected a existing tag (applying the blue .btn-primary style.

I've tried to apply the style during the select event (select2:select) event:

$("#ticker_select").on('select2:select', function(e) {
        // If the e.params.data.id equals e.params.data.txt,
        // then it is a user-created tag!
        if (e.params.data.id == e.params.data.text) {
            // User-created tag; Mark the tag red
            $(".select2-selection__choice[title='" + e.params.data.text + "']").addClass('btn-danger');

        }
        else {
            // User-selected tag; Mark the tag blue
            $(".select2-selection__choice[title='" + e.params.data.text + "']").addClass('btn-success');
        }
    });

I see that the styling applied to the tag but as soon as the event ends, select2 removes the style class reference. Can anyone please show me how to apply the styles to tags without select2 removing them? Many thanks!


回答1:


Reading the documentation & following a suggestion from IRC, there's a templateSelection option in select2. In my case, I would do something similar to this:

function template(data, container) {
    // If the ID and text properties are NOT equal, user didn't create tag
    if (data.id != data.text) {
       container.addClass("btn-primary");
    }
    else container.addClass("btn-danger");

    return data.text;
}

$('select').select2({
    templateSelection: template
});


来源:https://stackoverflow.com/questions/37822933/styling-individual-select2-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!