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

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

In jQuery, utilizing dynamic class names with variables

I have a series of images with unique classes such as: .1a .2a .3a .4a ..... I am looking to toggle some other classes named .1b .2b .3b .. and so on so that: '.1a' toggles to '1b' '.2a' toggles to &ap ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

Tips for retaining JWT token in local storage even after a page refresh

I am currently working on implementing a login/logout feature and utilizing the context API to manage functions such as storing tokens in local storage and removing them upon logging out. However, I have encountered an issue where the token stored in local ...

Issue with FontAwesome icon selection in Vue2 (nuxt) not displaying icons

If you're looking for the icon picker, you can find it here: https://github.com/laistomazz/font-awesome-picker I've tried running it, but unfortunately, the icons are not showing up. When I inspect the elements, the code is there but the icon is ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...

Sorting through a collection of subarrays

Within my application, the structure is set up as follows: [ ["section title", [{ item }, { item } ... ]], ["section title", [{ item }, { item } ... ]], ... and so forth When displayed in the view, the sections are placed in panels, with their internal ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...

How can I fix the 'Null is not an object' error that occurs while trying to assess the RNRandomBytes.seed function?

Currently, I am in the process of creating a mobile application using expo and react-native. One of the features I am working on involves generating a passphrase for users on a specific screen. To achieve this task, I have integrated the react-native-bip39 ...

The Concept of Interface Segregation Principle within jQuery

Could someone provide a clear explanation of how this function operates using jQuery? Especially in reference to the response found here. It seems similar to the Single Responsibility Principle (SRP) in Object-Oriented Programming. What sets it apart? ...

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...

Can a class be passed to the binding attribute in Angular framework?

We currently have a system in place that is dependent on a numeric value being set to either 1 or 2 in order to display specific icons. This method is functional. <span *ngIf="config.icon" [class.fas]="true" [class.fa-plus]="icon===1" ...

Ways to verify the contents of an NPM package

After successfully installing the npm package @mediapipe/camera_utils, I am now curious about how to explore the contents within it. Can someone guide me on how to achieve this? ...

I'm currently attempting to find a specific string within a URL

I want to utilize jQuery to search for a specific string that is appended to the end of the page URL after a user submits a form. Here's an example of what the URL might look like: https://somerandomsite.com/?page_id=1423#wpcf7-f1448-p1423-o1 The o ...

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...

What is the best way to cut out a portion of a div using CSS?

I have a scaled down version of my project, but it's not quite what I need. I would like the green div to have some transparency so that the content behind both divs is visible (there is none in the example, but there is in my actual project). However ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

How can I update two divs simultaneously with just one ajax call?

Is there a way to update 2 divs using only one ajax request? The code for updating through ajax is in ajax-update.php. <?php include("config.inc.php"); include("user.inc.php"); $id = $_GET['id']; $item = New item($id); $result = $item->it ...