Select2 Dropdown Options Do Not Update Background Color

I am currently implementing the Select2 Input CSS/jQuery framework from to assist me in handling multi-select boxes. However, I am facing difficulty in changing the background color of the results when the select box is clicked.

To provide a better understanding, I have prepared a JS fiddle:

https://jsfiddle.net/L26bzgmf/

This is the specific select box I am working on:

<select class="form-control select2-multi" name="tags" multiple="multiple">
    <option value="1">Tag 1</option>
    <option value="2">Tag 2</option>
    <option value="3">Tag 3</option>
    <option value="4">Tag 4</option>
</select>

When the box is clicked, I require all four tags to be displayed in white text with a background color of #333333. Subsequently, upon selection (as evidenced by the automatically selected Tag 1), I need the background color to transition to #666666, the font to remain white, and the "remove" x icon to also turn white with a hover effect of #aa0000.

I've experimented with both jQuery and CSS to achieve this outcome but so far, I haven't had any success. It's quite frustrating as their documentation was previously helpful, but now it seems perplexing. I am open to exploring alternative solutions that offer similar functionalities as Select2 for my tagging system within the blog.

This feature is being developed for implementing a "tags" system on my blog.

Answer №1

Success! I cracked the code and managed to alter the styling using only CSS. No JavaScript required!

/* Dropdown/DropUp Results */
.select2-container--default .select2-results>.select2-results__options {
    background-color: #555555;
    color: #eeeeee;
}

/* Clear "X" Button */
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
    color: #cccccc;
}

/* Hover Effect for "X" Button */
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
    color: #aa0000;
}
/* Styling for Each Result */
.select2-container--default .select2-selection--multiple .select2-selection__choice {
    background-color: #555555;
}

I attempted to update the JS Fiddle, but encountered obstacles. Here's a screenshot instead. :P

https://i.sstatic.net/kCDit.jpg

Answer №2

When you access the browser web console, the JQuery Select2 plugin performs the following actions:

  1. It adds a <span class="select2"> right after your .select2-multi

  2. It generates a <span class="selection"> with an id="

    $('span[aria-owns]', **'the span created at Step 1'**).attr('aria-owns')
    " under the document.body and then uses position=absolute to position it on top of your <select>

If you wish to customize anything, simply explore the above two DOM trees to make the desired changes.

Below is a demonstration:

$('.select2-multi').select2()
let select2Obj = $('.select2-multi+.select2')
$('span', select2Obj).css('background-color', '#666666')
$('.select2-multi').on('select2:open', function () {
  setTimeout(()=>{//some elements will be created after open, so have to use setTimeout
    let select2Obj = $('.select2-multi+.select2')
    //change the background-color for select
    //you can uncomment below codes to see its structure
    //console.log($('.select2-container').html())
    //below change the background color for all options
    $('#'+$('span[aria-owns]', select2Obj).attr('aria-owns'))
      .find('li')
      .css('background-color', '#333333')
    //below change the font color for all options
    $('#'+$('span[aria-owns]', select2Obj).attr('aria-owns'))
      .find('li')
      .css('color', 'white')
    $('#'+$('span[aria-owns]', select2Obj).attr('aria-owns'))
      .find('li')
      .hover(function(){
        $(this).css('color', 'black')
      }, function() {
          $(this).css('color', 'white')
        }
      )

    //below change the font color for the selected option
    $('#'+$('span[aria-owns]', select2Obj).attr('aria-owns'))
      .find('li[aria-selected=true]')
      .css('color', 'red')
    //below change the font color for <select>
    $('>span>span>span', select2Obj).css('color', 'blue')
    //below change the background color for the arrow of <select>
    $('>span .select2-selection__arrow', select2Obj).css('background-color', 'red')
    },0)
})

//customize the tags
$('.select2-multi').on('change', function () {
  $('ul li span', select2Obj).css('color', 'white')
  $('ul li', select2Obj).css('color', 'white')
  $('ul li', select2Obj).css('background-color', 'gray')
  $('ul li', select2Obj).hover(function(){
    $(this).css('background-color', '#aa0000')
  },function(){
    $(this).css('background-color', 'gray')
  })
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select class="form-control select2-multi" name="tags" multiple="multiple">
    <option value="1">Tag 1</option>
    <option value="2">Tag 2</option>
    <option value="3">Tag 3</option>
    <option value="4">Tag 4</option>
</select>

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

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...

Mistakes in my async/await workflow: How am I incorrectly loading and injecting this external script?

Encountering a simple problem: some calls to refresh() cause window.grecaptcha to become undefined. It doesn't happen all the time, probably due to network delays. Debugging this issue is proving to be tricky, especially since I'm still new to th ...

Is there a way I can put together this CSS code?

I am currently using Socialengine (Zend Framework) along with several plugins. However, one of the plugins has its own unique CSS style. There are multiple CSS cascades in use, but they are not less or sass files. The contents of my file style.css are as ...

transforming the accordion into a checkbox

https://i.sstatic.net/5y2gv.pngWhile working on my Angular application, I encountered an issue with using the Bootstrap accordion component. I am trying to make the accordion function as a checkbox, where when the checkbox is checked, the accordion expand ...

Receiving the message "servlet temporarily moved" while attempting to pass serializable data through an AJAX request to a servlet

Here is the code snippet I am using to send serializable data on an ajax call to a servlet: $.ajax({ type: "post", url: registersubmit.RegisterServlet.json, dataType: "json", data:$('#registrationForm').serialize(), ...

connecting parameters to functions in javascript

I'm attempting to execute a second query once the first query has been resolved by using the following code: const task1 = nextQuery => $.get('1.json', data => nextQuery()); const task2 = nextQuery => $.get('2.json', ...

What is the best way to retrieve the value of a nested function in JavaScript?

I am currently working on a project that involves a function. function findParentID(parentName) { Category.findOne({ categoryName: parentName }, function (err, foundParent) { var parentID = foundParent.categoryID;    return parentID;<br> } ...

Implementing event listener for component generated by mapping function

I am using the map function in Javascript to render a list, but I am struggling to add a click listener to the elements in that list. Check out the code here - https://codesandbox.io/s/oqvvr1n3vq My goal is to log Hello to the console whenever the h1 tag ...

Utilizing Bootstrap 5 with either a 16 or 24 column grid system minus the need for Sass

I'm looking for assistance in adjusting Bootstrap 5 to have either a 16 or 24 column grid rather than the default 12 columns. I attempted using Bootstrap Customize but found it to be an older version. I want the flexibility to change the grid from 12 ...

Retrieve content from external webpage and direct it to domain.tld/?id=

I am looking to retrieve the body content from an external webpage in plaintext format. After that, I plan to use this value for making an API call. For example: xyz.com/?id=<plaintext from external page> ...

Guidelines for executing a PHP script upon a button click

I am new to learning PHP. I have a jQuery code that I need to implement in PHP. The active class simply changes display:none to display:block. You can find the code here. $(document).ready(function(){ $(".cecutient-btn").click(function(){ event. ...

CSS: The sub-class functionality is not functioning as intended

Having trouble with this HTML element : <span class="item-menu-notif non-lue" onclick="dosomething(2150)"> TEXT </span> These are the CSS classes : .item-menu-notif{ display: block; cursor: pointer; padding: 0 0.4em 0 0.4em; } s ...

Dynamically assigning values to class properties in Angular with Typescript is a powerful

I am working on a project where I have a class and a JSON object. My goal is to update the properties in the class based on the values in the JSON object, using Angular 9. This is the class: export class Searchdata{ name:boolean=false; age:boolean=fa ...

When a user right-clicks to open a context menu, extract a specific cell value from a row in a dynamically generated datatable

I am utilizing an Ajax sourced datatable from here to display my content. In addition, I have implemented a customized context menu (more information here) on the datatable that is dynamic as per my requirements. The goal is to populate context menu item ...

Moment-Timezone defaults to the locale settings after the global Moment locale has been established

I am currently developing an application using Typescript that requires features from both Moment.js and moment-timezone. To localize the date and timestamps within the application, I have set moment's locale in the main app.ts file to match the langu ...

Remove numerous entries from the WordPress database by selecting multiple checkboxes

A new customer table named "tblvessel" has been created in the Wordpress database. The code provided below selects records from the database and displays them as a table with checkboxes next to each record, assigning the record's 'ID' to the ...

Achieving second class using jQuery from a choice of two

Looking for assistance with retrieving the second class from an element that has two different classes. I attempted to use the split method but encountered some issues, can anyone provide guidance? js_kp_main_list.find('li#kp_r_04').addClass(&ap ...

Difficulties with validating phone numbers

I'm having an issue with my JavaScript code that is supposed to validate a phone number field, but it doesn't seem to be working. Even if I enter incorrect values, the form still submits. Here's the snippet of my code: <script> functi ...

Z-index malfunctioning - need to troubleshoot

Check out my website at Upon visiting the website on a PC, you'll notice that the navigation menu appears on the loader. Can anyone explain why this is happening? The only modifications I made to my CSS are: <style> .navbar-inverse { backg ...

5 horizontal navbar with dropdown menu in Bootstrap

I am currently utilizing bootstrap 5. Is it possible to display my navbar menus horizontally like the image provided? show submenus horizontally as shown in this picture I would also like to implement submenu for other submenus up to 4 levels deep. Any ...