Is it possible to customize the background color of select2 boxes separately for each option?

I recently implemented the select2 plugin and now I'm looking to add a new class within the .select2-results .select2-highlighted class in order to change the background color. Does anyone have any suggestions on how to achieve this?

Answer №1

If you want to style different select2 boxes with different colors, it can be a bit tricky due to how select2 generates HTML and adds it to the document:

According to the documentation:

By default, Select2 attaches the dropdown to the end of the body and positions it below the selection container using absolute positioning.

Even though the dropdown is attached to the body by default, Select2 can display above the container if there isn't enough space below but ample space above it. It's not restricted to displaying within the parent container, making it suitable for rendering inside modals and other small containers.

While this makes select2 more compatible with modals, it also means styling descendants of the original select's parent won't work as expected.

However, you can use the dropdownParent option to specify where the generated HTML should be added.

The solution involves adding a data-select2-container="" attribute to each select element that should have a different colored select2 counterpart. This code snippet will then create a div with the specified class in the attribute, insert it after the original select element, and append the select2 box as its child. This allows you to style elements as children of a div with the designated class:

$(function () {
     $(".select2").each(function(i,e){
         $this = $(e);
         if($this.data('select2-container')){
          // if a container was specified as a data attribute, create that container and add it after the current raw select element
         // the value set for `data-select2-container` will be used as the class for the container
             $('<div class="'+$this.data('select2-container')+'"></div').insertAfter($this);
             $this.select2({
           placeholder: 'Select an option...',
          dropdownParent:$this.next() // set the parent for the generated html to the element we created
     });
         } 
         else $this.select2({ placeholder: 'Select an option...'}); // handel cases where a container was not specified 
     });
});
.orange .select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: orange;
}

.red .select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: red;
}

.green .select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<div class="container1">
    <select class="select2" data-select2-container="orange">
        <option></option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
        <option value="5">Option 5</option>
    </select><br>
    <div class="container2">
        <select class="select2" data-select2-container="green">
            <option></option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
        </select><br>
        <select class="select2" data-select2-container="red">
            <option></option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
        </select>
    </div>
        
</div>
<br>

Key points to note:

  1. This code is designed for the full version of select2 4.0.0 (and its corresponding CSS )
  2. Elements added using this method may not behave as expected if placed within a modal (as per the comments in the documentation, albeit untested)
  3. In such scenarios, modifying the plugin directly might be a viable option to include this functionality natively, given the absence of an existing option for it in the original plugin code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating small image previews in JavaScript without distorting proportions

I am currently working on a client-side Drag and Drop file upload script as a bookmarklet. To prepare for the upload process, I am utilizing the File API to convert the images into base64 format and showcase them as thumbnails. These are examples of how m ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

Using string literals in Vue and HTML classes

When a user attempts to log in with the wrong password, I want multiple alert popups to appear on the UI instead of just one. This will help the user understand if they are still entering the incorrect password. To achieve this, I decided to use a counter ...

"Discovering the data-id of an active class is essential - here

<ul class="deal-menu"> <li class="active" data-id="today-spl"><a href="#" class="first">Special<span class="active"></span></a></li> <li class="" data-id="today-deal"><a href="#">Deal</a>< ...

Trouble with importing scss file in sass and bootstrap collaboration

I am using Sass with Bootstrap 4, and now I'm facing an issue in my Sass folder where I have an app.scss file that includes: @import _customVariables.scss @import node_modules/bootstrap/scss/functions @import node_modules/bootstrap/scss/mixins Howev ...

Navigating the absence of Prismic's ability to use the <blockquote> element in their rich text editor

My experience with Prismic as a headless CMS has been mostly positive, but I recently encountered an issue that surprised me - the lack of support for a simple blockquote. It's baffling to me that such a basic HTML element is not natively supported by ...

Tips for selecting the correct date on a DatePicker using selenium?

I am facing an issue with my selenium test related to a date picker on a webpage. The task is to select a specific date (e.g., 14/2/2012) by clicking on the correct day. However, the date picker is generated using jQuery as shown in the code snippet belo ...

Error: The studentsList is not iterable. Issue encountered during Jasmine Unit Testing in Angular 2

How can I effectively test the forEach loop in jasmine with karma? Below is the code for the component: getData(studentsList:any, day:any, game:any){ let strength:any; let location:string; if(studentsList){ studentsList.forEach( value =& ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

conceal a targeted section from the bottom of the iframe

I have a website embedded inside an iframe for use in a webview application. <body> <iframe id="iframe" src="http://www.medicamall.com"></iframe> </body> This is the CSS code: body { margin:0; padding:0; height:10 ...

Although the ng-click HTML code functions as expected, the same code within an AngularJS function does not seem to work properly

HTML <div id="rightpane"> <div id="rightpanecontent" > <div id ="Addbtn" style="text-align: right;"> <button type="btnAdd" class="btnAddText" ng-click="addText()" style="margin-top:10px;margin-left:166px; color: white;b ...

Modify the appearance of HTML dialog box using CSS styling

Currently, I am working on a Java Spring project that includes a single CSS file consisting of around 1500 rows. Recently, I was tasked with adding a dialog box to one of the screens in the project. The issue I encountered is that the style of the dialog b ...

When using the navbar in Tailwind CSS, the image is appearing distorted instead of aligning properly with the adjacent

I am trying to add a flag, login button, and sign up button Using class="flex", I placed an image inside it However, when I add the buttons, the image gets distorted. How can I prevent this? Expected Outcome I want to create the flag, login but ...

Unusual issue with jQuery's AJAX functionality

Utilizing jQuery AJAX, I am fetching data from a PHP page and displaying a loading GIF image in the placeholder to indicate that results are being processed. $(".project").change(function(){ $(".custName").html("<img src='/admin/images ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

The HTML unit is unable to locate the form for unknown reasons. My suspicion is that it could be due to the presence of Angular

Struggling with using HTMLunit to login and upload a file. Successfully logged in but unable to locate the form, despite it being present on the HTML page. Here is the JAVA CODE snippet: public static void main(String[] args) { WebClient webClient = ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

How can I select a checkbox using jQuery?

I need help toggling a checkbox on and off using jQuery. Here is the HTML code: <input type="checkbox" id="isWorking" name="isWorking" /> I attempted to control it with jQuery like this: $('#isWorking').prop('checked', true); $ ...

Eliminate borders for text input in Bootstrap 3 styling

Trying to eliminate the top, right, and left borders for text input fields in Bootstrap 3. The selector being used is as follows: input[type="text"] { border-top: 0; border-right: 0; border-left: 0; } However, in Chrome, a faint thin line is ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...