Having difficulty modifying the font color on a Select2 dropdown that includes custom attributes

Recently, I have been exploring the integration of Select2 in an older application. I have successfully converted the old dropdown into a Select2 dropdown and everything seems to be functioning properly. The dropdown is populated with options and all related functions are working as expected. However, I am now looking to implement a more advanced feature.

In the original dropdown, each option is equipped with a custom attribute:

<option onlyslave="True" ...> ...</option>

I am aiming to change the text color to red if the 'onlyslave' property is set to true. If it's false, the text should remain black. I have managed to make the text red by utilizing the following CSS code:

.select2-results { 
  color: red;
}

However, applying an attribute selector [onlyslave="true"] does not yield the desired outcome. Despite having 'False' and 'True' values within the options of the 'old' dropdown, the text does not turn red. Additionally, variations in capitalization such as 'Truth' or 'truth' do not affect the result.

.select2-results[onlyslave="true"] { 
  color: red;
}

If anyone has suggestions on how to achieve this functionality, please share your insights. I have found the Select2 documentation to be somewhat lacking in this area. My current version of Select2 is 4.0.5, but I am open to downgrading if necessary.

Answer №1

To create your element, remember to utilize the templateResult property as mentioned in my previous comment, and make sure to consider the onlyslave attribute. Here's an example:

HTML

<select>
  <option onlyslave="True">Option 1</option>
  <option onlyslave="False">Option 2</option>
  <option onlyslave="False">Option 3</option>
</select>

CSS

.select2-results span[onlyslave="True"] { 
  color: red;
}

JavaScript

function formatState (state) {
  if(!state.element) return;
  var os = $(state.element).attr('onlyslave');
  return $('<span onlyslave="' + os + '">' + state.text + '</span>');
}

$(document).ready(function() {
    $('select').select2({
      templateResult: formatState
    });
});

Check out this Codepen example for a live demonstration: https://codepen.io/anon/pen/gXByeK

Answer №2

Check out this functional code snippet that demonstrates how to achieve the task you inquired about. One of the previous responses mentioned utilizing the templateResult functionality of select2 for proper implementation. Select2 operates by concealing your original select element and creating a customized version for display. This customized version lacks the onlyslave attribute present in your original select element, causing your CSS selector to be ineffective.

Here is an example of the HTML:

<select class="js-example-basic-single" name="state">
  <option onlyslave="True">test</option>
  <option>test 2</option>
</select>

And here is the corresponding JavaScript:

function formatState (state) {
  if (!state.id) {
    return state.text;
  }

  var $state
  if(state.element.attributes.onlyslave && state.element.attributes.onlyslave.value == "True"){
    $state = $('<span class="redtext">'+ state.text+ '</span>');
  }

else {
  $state = $('<span>'+ state.text+ '</span>');
 }
  return $state;
};


$('.js-example-basic-single').select2({
  templateResult: formatState
});

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

Use VueJS v-on:click and Vanilla JS to collapse various divs when clicked

Can VueJS and vanilla JS be used to collapse specific divs among many? I have information contained in separate card elements that include a title and a body. My goal is to make the body of each card expand or collapse when the respective title is clicked ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

The TypeScript script does not qualify as a module

Just starting out with TypeScript and encountering a simple issue. I'm attempting to import a file in order to bring in an interface. Here's an example: Parent: import { User } from "@/Users"; export interface Gift { id: number; ...

Using ng-non-bindable along with ng-if in Angular Google Maps allows for certain elements or

I recently came across an interesting discussion on the necessity of ng-non-bindable for the <ui-gmap-windows> element in Angular Google Maps. It shed some light on how ng-non-bindable is utilized in the directive. However, I encountered an issue wh ...

jquery global variable not working as expected

I'm having trouble making some variables global outside the jQuery function. I've tried using 'var' to declare them first and then assigning values, but when I try to log() them at the end, I get undefined. var lat, lon; $.get('ip ...

Quiz timer using JavaScript

In my HTML and JavaScript project, I am creating a quiz game where players have 15 seconds to answer each question. To implement this timer feature, I used the following code snippet: <body onload="setTimeout(Timer,15000)"> Implemented in JavaScrip ...

A peculiar issue is occurring in Vue.js where a value within a v-for loop seems to be losing association with the intended array

During my third day of working with Vue.js, I decided to create a basic application for requesting car keys in a service department. Although I am aware that there are areas in the code that could be improved, I encountered a specific issue that I need ass ...

Leveraging personalized styles in Kendo UI

Currently, I am utilizing the robust Kendo UI HTML Framework within my web application for its exceptional support of MVVM functionality. While I appreciate the convenience that Kendo offers with MVVM, I am in need of a solution that allows me to leverage ...

Enhance the impact of "dialogs" to the fullest extent or minimize it to achieve the

How can I position the minimized dialog on the bottom of the div when appending dialogs next to each other in a FB messaging system? To achieve a Facebook messaging effect, the titlebar must go down when minimizing/maximizing the dialog. Perform the follo ...

Solution for problem with IE scrollWidth

Encountered a peculiar bug in IE where the scrollWidth is consistently off by 1px compared to the offsetWidth. This anomaly appears to be triggered by the length of text/characters within the element, specifically when overflow is set to something other th ...

What is the best approach for dynamically updating JSON values using user input in jQuery?

I have implemented a feature where users can enter values into 3 text boxes and upon clicking the add button, these values are added to a new JSON object and displayed in a table. Additionally, users can edit specific fields in the table which should updat ...

Ways to align a div vertically in relation to the remaining space's height

After successfully creating a webpage with a "sticky" footer using flexbox, I am now challenged with centering the content within the remaining height (vh - navbar height - footer height) when the content is small. Check out the image below for a visual re ...

Implement an AJAX link on the webpage using Yii framework

I'm currently working on developing a user interface for an application, and I've encountered an issue with my code that involves adding AJAX links using a Yii helper function. echo CHtml::ajaxLink('Link', array('getajaxlinks&apos ...

Using jQuery and Django to send a list of numbers in order

My task list is simple, allowing users to choose their preferred order for tasks. I need to send all the tasks' IDs in that specific order to the server from a JavaScript array and fetch the values in a Django view. In essence, what is the most effi ...

Seeking assistance with exporting a Vue single file component that relies on Swiper.js for functionality

I'm having trouble figuring out how to properly export a Vue SFC that includes the mySwiper object. I would appreciate seeing an example from someone who has experience with this. Below is the JavaScript portion of my SFC <script> import Swiper ...

Tips for choosing the dropdown selection on an ASPX website page

I have a specific dropdown menu set up, and I need to select the appropriate option from the viewdata object in my .aspx page. Here is what my menu looks like: <td headers="Vehicle" style="background-color:#EFF3FB;font-family: Verdana; font-size: 10px ...

Switching the background image with a single click and reverting it back with a double click using jquery

I am working on a project with multiple div elements which need their background images to change upon clicking and revert back to the original image when clicked again. Below is the CSS code for one of the divs, including its Class and ID: .tab_box { wid ...

Examining components that are lazily initialized using Jest

Currently, I am in the process of testing a lazily initialized component that has been created with react-lazy-load-image-component using JestJS. Below you will find the tests that I have implemented: const viewModel = new VehicleViewModel(vehicleData, {}) ...

A javascript text slider that dynamically updates text content sourced from PHP

Currently, I am in the process of developing a project that involves creating a dynamic slideshow of testimonials for my website. To achieve this, I am utilizing PHP and MySQL for the database backend. My goal is to use pure JavaScript to efficiently showc ...

Ways to prevent the navbar from disappearing when the Chrome browser is resized

I am looking to align the navbar lists, which are currently on the right side, below the header icon placed on the left side. Rather than toggling the navbar with a button, I want it to simply expand under the header icon. It seems that the disappearance ...