Changing the background color of a select2 selection within the select field

为君一笑 提交于 2019-12-11 02:27:42

问题


I am using Select2 to setup multi-select tag type fields in my application. I know which CSS attribute changes the colors of the selection box once it is placed in the select field:

selection box color

.select2-container--default .select2-selection--multiple .select2-selection__choice {
    background-color: #e4e4e4;
    border: 1px solid #aaa;
    border-radius: 4px;
    cursor: default;
    float: left;
    margin-right: 5px;
    margin-top: 5px;
    padding: 0 5px
}

What I am trying to figure out is how to have this change based on the selection a user makes. The selection list is pre-defined.

Tried something like this:

JavaScript to initialize / change box color

$(document).ready(function () {
        $('#test').select2();
        $('.select2-container--default .select2-selection--multiple .select2-selection__choice').each(function () {
            var title = $(this).attr('title');
            console.log(title);
            if (title === 'Breakfast') {
                $(this).parent().css({ 'background-color': "green" });
            }
            if (title === 'Brunch') {
                $(this).parent().css({ 'background-color': "red" });
            }
            if (title === 'Lunch') {
                $(this).parent().css({ 'background-color': "blue" });
            }
        });
    });

This does not appear to work. Has anyone tried styling the tag boxes for Select2?


回答1:


Change $(this).parent().css('background-color', 'green');

by $(this).parent().css({ 'background-color': "green" });

And the same with the rest.



来源:https://stackoverflow.com/questions/45946496/changing-the-background-color-of-a-select2-selection-within-the-select-field

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