Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the css of color of select2 tags?

I just started using project for showing multiple tags from a select box and it works great, thanks for the library.

I just need to modify the color or css of the tags shown in multi-value select-boxes. Right now the color of the tag is shown as grey and I would like to change that to some other color according to the type of the tag. Or at least is there a way to change the default color?

Also is it possible to change the css class of tags? There is an option such as formatResultCssClass but when I tried to add css classes through that property nothing changed, I would appreciate if someone can show an example how to do this?

Edit: Workaround for solving the problem: Add a new property to the select2.defaults for representing classes of selected objects.

$.fn.select2.defaults = {
...
    selectedTagClass: "",
...
}

addSelectedChoice: function (data) {
        var choice=$(
            "<li class='select2-search-choice " + this.opts.selectedTagClass + "'>" +
            "    <div><a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'><i class='icon-remove icon-white'/></a></div>" +
            "</li>"),
        id = this.id(data),
        val = this.getVal(),
        formatted;
...

And initialize select2 using this new property:

$(".#select2Input").select2({placeholder: "Please Select Country", 
                    selectedTagClass: 'label label-info', // label label-info are css classes that will be used for selected elements
                    formatNoMatches: function () { return "There isn't any country similar to entered query"; }
                });
like image 919
cubbuk Avatar asked Jan 15 '13 14:01

cubbuk


6 Answers

For formatting the tags you can use the function formatSelectionCssClass.

$("#mySelect").select2({
    formatSelectionCssClass: function (data, container) { return "myCssClass"; },
});

Or you could add a css class based on the option id:

$("#mySelect").select2({
    formatSelectionCssClass: function (data, container) { return data.id; },
});

Remember that you will need to override both filter and background_color in your css class

like image 185
trgt Avatar answered Oct 02 '22 10:10

trgt


First up - a warning that this means you are overriding the CSS that is internal to select2, so if select2 code changes at a later date, you will also have to change your code. There is no formatChoiceCSS method at the moment (though it would be useful).

To change the default color, you will have to override the various CSS properties of the tag which has this CSS class:

.select2-search-choice {
    background-color: #56a600;
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f4f4', endColorstr='#eeeeee', GradientType=0 );
    background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
    background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
    background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
    background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
    background-image: -ms-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
    background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
    -webkit-box-shadow: 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
    -moz-box-shadow: 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
    box-shadow: 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
    color: #333;
    border: 1px solid #aaaaaa;
}

To change the class of each tag based on the text or option # of that tag, you will have to add a change event:

$("#select2_element").on("change", function(e) { 
      if (e.added) {
          // You can add other filters here like
          // if e.val == option_x_of_interest or
          // if e.added.text == some_text_of_interest
          // Then add a custom CSS class my-custom-css to the <li> added
          $('.select2-search-choice:not(.my-custom-css)', this).addClass('my-custom-css');
      }
});

And you can define a custom background-color etc in this class:

li.my-custom-css {
       background-color: // etc etc
}
like image 35
mccannf Avatar answered Oct 04 '22 10:10

mccannf


In my case I needed to show the difference between tags that were "selected" and those which were being added.

The help here was for the previous versions of select2, and not of much use. Using the current 4.0 version (with its terribly sparse documentation) I was able to achieve this using the template functions and a little bit of 'cleverness'.

First step is to template the results (it should be noted that on every select or remove action this is fired for every selection in the box). This normally returns JUST the text that will go in the resulting LI... however we want to wrap that text in a span (and tell S2 not to strip the HTML out by returning an object) with a custom CSS class for our type. In my example I use the selected property to determine this:

$('.select2_sortable').select2({
    tags: true,
    templateSelection: function(selection) {
        if(selection.selected) {
            return $.parseHTML('<span class="im_selected">' + selection.text + '</span>');
        }
        else {
            return $.parseHTML('<span class="im_writein">' + selection.text + '</span>');
        }
    }
});

Your resulting HTML after an item is selected should be something like this:

<ul class="select2-selection__rendered ui-sortable" id="select2_rendered_smartselectbox_4">
    <li class="select2-selection__choice" title="John Doe">
        <span class="select2-selection__choice__remove" role="presentation">×</span>
        <span class="im_selected">John Doe</span>
    </li>
    <li class="select2-selection__choice" title="fdfsdfds">
        <span class="select2-selection__choice__remove" role="presentation">×</span>
    <span class="im_writein">fdfsdfds</span>
    </li>
    <li class="select2-search select2-search--inline ui-sortable-handle">
        <input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" placeholder="" style="width: 0.75em;">
    </li>
</ul>

But this isn't enough, as we need to access the parent LI, not the span child. And since CSS doesn't allow for parent selectors, we have to run some jQuery to make it happen. Because these are redrawn we'll want to run this function on both the select and remove events of the Select2 item:

$('.select2_sortable').on("select2:select", function (ev) {
    updateSelectedParents();
});
$('.select2_sortable').on("select2:removed", function (ev) {
    updateSelectedParents();
});

function updateSelectedParents() {
    $('.im_selected').closest('li').addClass('im_connected_item');
    $('.im_writein').closest('li').addClass('im_writein_item');
}

Finally resulting in:

<ul class="select2-selection__rendered ui-sortable" id="select2_rendered_smartselectbox_4">
    <li class="select2-selection__choice im_connected_item" title="John Doe">
        <span class="select2-selection__choice__remove" role="presentation">×</span>
        <span class="im_selected">John Doe</span>
    </li>
    <li class="select2-selection__choice im_writein_item" title="fdfsdfds">
        <span class="select2-selection__choice__remove" role="presentation">×</span>
    <span class="im_writein">fdfsdfds</span>
    </li>
    <li class="select2-search select2-search--inline ui-sortable-handle">
        <input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" placeholder="" style="width: 0.75em;">
    </li>
</ul>

And allowing you to style your elements based on the im_writein_item and im_connected_item CSS classes.

like image 41
Denny Avatar answered Oct 04 '22 10:10

Denny


You can access the tag container like this:

formatSelectionCssClass = function(tag, container) {
    $(container).parent().addClass("my-css-class");
};
like image 26
Leo Avatar answered Oct 04 '22 10:10

Leo


Use the formatResultCssClass, containerCssClass and dropdownCssClass options to specify classes in code, the adaptContainerCssClass and adaptDropdownCssClass options to specify classes in markup, or even the containerCss and dropdownCss options to specify inline style in code.

If you're wondering why you never used those, they weren't properly documented a while ago.

Reference: <http://ivaynberg.github.io/select2/>

like image 41
tne Avatar answered Oct 02 '22 10:10

tne


For those that only want to change the color of some of the select2 boxes:

Instead of directly modifying the Select2 CSS properties of select2-choice directly, use the ID generated by select2 for the select2 div (this will be #s2id_yourelementid) to select its children carrying the select2-choice class.

For example, if I want to modify an element, #myelement, that I apply Select2 to, then to change the color, I would add the following to my css:

#s2id_myelement > .select2-choice{
     background-color:blue;
} 
like image 31
ManGI1 Avatar answered Oct 01 '22 10:10

ManGI1