最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - select2 - color tag based on selection order - Stack Overflow

programmeradmin2浏览0评论

I have a drop down select input (built using the select2 plugin), and my goal is that each of the selected tags take on a color, in order to help readability. For instance, the first selected tag would be blue, the second would be red etc.

I don't manage to do it, for at least two reasons:

  • how to access (DOM manipulation) the selected tags? I can access children of the select elmt and check whether they are selected (using the data-select2-id ? How does this one work btw, I can't explain myself the values it takes in the example below), but since I have 10000+ possibilities and expect 2 or 3 selections this seems like a sub-optimal approach.

  • how to specify their color?

I read here, how to change the background color of my input, but that is not at all what I am trying to do.

In fact I need the tag to take on a particular color so that the user can map it to it corresponding coloured entry in a chart.

Can you tell me how to fix this minimal example (fiddle) to have this please?

A similar question exists but it has not been answered, and it has no minimal example.

ADD: According to that thread, a solution could be to give a color to each of the possible options as in the following. But since I have a large number of possible options, this does not really do..

option.line1 {
    background-color: #000000;
    color: #ffffff;
}

option.line2 {
    background-color: #000000;
    color: #ffff00;
}


<option class="line1" value="menu1">Menu Item 1</option>

I have a drop down select input (built using the select2 plugin), and my goal is that each of the selected tags take on a color, in order to help readability. For instance, the first selected tag would be blue, the second would be red etc.

I don't manage to do it, for at least two reasons:

  • how to access (DOM manipulation) the selected tags? I can access children of the select elmt and check whether they are selected (using the data-select2-id ? How does this one work btw, I can't explain myself the values it takes in the example below), but since I have 10000+ possibilities and expect 2 or 3 selections this seems like a sub-optimal approach.

  • how to specify their color?

I read here, how to change the background color of my input, but that is not at all what I am trying to do.

In fact I need the tag to take on a particular color so that the user can map it to it corresponding coloured entry in a chart.

Can you tell me how to fix this minimal example (fiddle) to have this please?

A similar question exists but it has not been answered, and it has no minimal example.

ADD: According to that thread, a solution could be to give a color to each of the possible options as in the following. But since I have a large number of possible options, this does not really do..

option.line1 {
    background-color: #000000;
    color: #ffffff;
}

option.line2 {
    background-color: #000000;
    color: #ffff00;
}


<option class="line1" value="menu1">Menu Item 1</option>
Share Improve this question edited Jan 8, 2018 at 11:14 hartmut asked Jan 4, 2018 at 20:02 hartmuthartmut 98212 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

I suggest to use selection templating, so you can customize the appearance of selected results by using the templateSelection configuration option.

In your case you can operate on container parameter of templateSelection function like below:

templateSelection: function (data, container) {
    $(container).css("background-color", colors[data.id]);
    return data.text;
}

Here is a plete snippet coloring selected tags based on their id:

var colors = ["red", "blue", "green", "orange", "yellow"];

$(document).ready(function() {
  var checkList = [1, 3];
  $("#myList").select2({
  	width: "100%",
    templateSelection: function (data, container) {
      $(container).css("background-color", colors[data.id]);
      return data.text;
    },
  }).val(checkList).trigger("change");
})
.select2-selection__choice {
  color: white;
}
<link href="https://maxcdn.bootstrapcdn./bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>

<div class="container">
  <select multiple="multiple" id="myList">
    <option value="1">Apple</option>
    <option value="2">Mango</option>
    <option value="3">Orange</option>
  </select>
</div>

Or your fiddle updated: https://jsfiddle/beaver71/n9todvv8/


Update:

Below is a plete snippet coloring selected tags based on their position in selection.

In the code below the select2:select event handler prevents the Select2 plugin sorting the selection, so that tags appear in the order in which they were selected:

var colors = ["red", "blue", "green", "orange", "yellow"];

$(document).ready(function() {
  var checkList = [1, 3];
  $("#myList").select2({
  	width: "100%",
    templateSelection: function (data, container) {
      var selection = $('#myList').select2('data');
      var idx = selection.indexOf(data);
      console.log(">>Selection",data.text, data.idx, idx);
      data.idx = idx;
      
      $(container).css("background-color", colors[data.idx]);
      return data.text;
    },
  }).val(checkList).trigger("change");

  
  $("#myList").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);

    $element.detach();
    $(this).append($element);
    $(this).trigger("change");
  });
  
})
.select2-selection__choice {
  color: white;
}
<link href="https://maxcdn.bootstrapcdn./bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare./ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<div class="container">
  <select multiple="multiple" id="myList">
    <option value="1">Apple</option>
    <option value="2">Mango</option>
    <option value="3">Orange</option>
    <option value="4">Banana</option>
    <option value="5">Kiwi</option>
  </select>
</div>

New fiddle: https://jsfiddle/beaver71/phabypbt/


Reference:

  • Select2 issue: In multi-select, selections do not appear in the order in which they were selected
  • Select2: How to prevent tags sorting

This can be a solution or can be a point of start for you, please take a look, here i'm getting all choices selected, and using a loop i'm setting colors to it using the select2 id:

    var colors = ["red", "blue", "green", "cyan", "orange", "aliceblue", "purple"]; 
    //random colors that i created

    var selections = $(".select2-selection__choice");
    //this above will return all selections

    if (selections.length){
       for (var i = 0; i < selections.length; i++){
            var selection = selections[i];
            var selectionJQ = $(selection);
            var select2ID = selectionJQ[0].dataset.select2Id;   //here you can get some infos from select2  
            colorName   = colors[select2ID];

            selectionJQ.attr("style", "background: " + colorName + " !important");
        }
    }

Here's a fiddle to see if is that what you need: https://jsfiddle/nw0rd0dk/

EDIT
To help with the questions you posted in the ments, I created a new fiddle. https://jsfiddle/bdotckdu/

1) the simpler way I found is to encapsulate every select with a div, then find just the child choices from the select that is inside the single div (the fiddle will help to understand)
2) It works, you had an error in the fiddle that was causing it to not work, i fixed it.

发布评论

评论列表(0)

  1. 暂无评论