Set a different color for each tag.

I have select2 where users can select tags from a list or add new tags. When the user inserts a new tag, I write it to the database. The user can edit this tag from another screen and associate it with color. So my β€œtag” objects look like this:

{id:1, text:"cool tag", color:"#336699"} 

What I would like to do is show tags with their colors inside select2. I tried to do

 formatSelection: function (tag) { return '<div style="background-color:'+tag.color+'">' + tag.text + '</div>'; }, 

but this does not change the background color of the div that the tag itself contains.

I also know that I can use formatSelectionCssClass to add a CSS class for each element, but in this case, since the colors are created by the user, I do not have css classes (although if this is the only way, this is what I will do, I will dynamically generate the file css).

(PS .: It looks like a solution, but I was looking for something more elegant)

+6
source share
1 answer

Ok, I found a way to do this:

 data = function(){ return [{id:1, text:"tag 1", color:"#555555"}, {id:2, text:"tag 2", color:"#336699"}] }, formatSelectionCssClass = function(tag, container) { $(container).parent().css({ "background-color": tag.color }); }; 
+6
source

Source: https://habr.com/ru/post/972953/


All Articles