Changing the Background Color of a Dropdown List Element Using JQuery Depending on the Title

Initially, the code consisted of a plain table with a select tag:

<table class="table">
    <tr>
        <td>
            <select id="e2">
                <option value="green">Green</option>
                <option value="yellow">Yellow</option>
                <option value="red">Red</option>
            </select>
        </td>
    </tr>
</table>

Using jQuery functions, the selection is transformed into a list of nested spans:

<table class="table">
    <tr> 
        <td>
            <b class="tablesaw-cell-label">Status</b>
            <span class="tablesaw-cell-content">
                <select tabindex="-1" class="select2-hidden-accessible" id="e2" aria-hidden="true">
                    <option value="green">Green</option>
                    <option value="yellow">Yellow</option>
                    <option value="red">Red</option>
                </select>
                <span class="select2 select2-container select2-container--default select2-container--below" style="width: 64px;" dir="ltr">
                    <span class="selection">
                        <span tabindex="0" class="select2-selection select2-selection--single" role="combobox" aria-expanded="false" aria-haspopup="true" aria-labelledby="select2-e2-container">
                            <span title="Green" class="select2-selection__rendered" id="select2-e2-container">Green</span>
                            <span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
                        </span>
                    </span>
                    <span class="dropdown-wrapper" aria-hidden="true"></span>
                </span>
            </span>
        </td>
    </tr>
</table>

I want to dynamically change the background color of each element based on its title after the page loads. Below is the current function for changing colors. It executes once the dropdown list is created and formatted by the select2 functionality.

$(document).ready(function () {
    $('#e1').select2();
    $('#e2').select2();

    $('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
        var title = $(this).attr('title');
        console.log(title);
        if (title === 'Green') {
            $(this).parent().css('background-color', 'green');
        }
        if (title === 'Yellow') {
            $(this).parent().css('background-color', 'yellow');
        }
        if (title === 'Red') {
            $(this).parent().css('background-color', 'red');
        }
    });
});

While I've managed to simplify the code and apply a uniform color to all elements, my goal is to individually style each selection element based on its title without affecting others. This remains a challenge.

Answer №1

It seems like this code snippet aligns with what you were looking for in your previous post that was removed:

$(document).ready(function () {
    $('#e1').select2();
    $('#e2').select2().on('change', function(){
        $(this).next().find('.select2-selection').css({
            backgroundColor: this.value
        });
    }).trigger('change');
});

You just need to capture the change event and adjust the CSS accordingly.

Check out the updated demo linked in your original post: https://jsfiddle.net/jmarikle/ea7q41k7/

Answer №2

After reviewing the HTML structure that Select2 generates, it appears that your selector is not accurate. The classes select2-selection and select2-selection--single are both applied to the same element, so you should replace the space between them with a class selector, ..

Furthermore, the if statement is unnecessary as the title attribute already corresponds to the color being set using .css(). Consider the following code snippet:

$('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
    var title = $(this).attr('title');
    $(this).parent().css('background-color', title);
});

Check out a working example here

Answer №3

It seems like you forgot to include the . in your selector, which is why it's not working properly.

To fix this issue, please try using the following code:

$('.select2-selection.select2-selection--single span.select2-selection__rendered')

Instead of the code you originally had:

$

('.select2-selection select2-selection--single span.select2-selection__rendered')

Answer №4

Here is a sample code that can be implemented in any function or customized to suit your needs.

$('#element2').on('click', function(){
    var title = $(this).attr('title');
    $(this).css('background-color', title);
});

I originally used val() in this code, but feel free to modify it as needed. Access the JSFIDDLE HERE

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 Backbone.js, the append method replaces the existing HTML content instead of simply adding an

As a beginner in backbone.js, I decided to start building a small todo application using examples from the "Backbone fundamentals" by Addy Yosmani. However, I encountered an issue with my code where instead of appending each item to the list view, it repla ...

How can the $spacer variable in Bootstrap be modified?

My attempt to adjust the $spacer variable in SASS to increase margins seems to be failing. Here is my code: @import url(../node_modules/bootstrap/scss/_functions.scss); @import url(../node_modules/bootstrap/scss/_variables.scss); @import url(../node_module ...

Develop an innovative Angular 8 application with a dynamic combination of Bootstrap 4 and Angular Material 8 grid

Recently, I created an Angular 8 project using the Angular CLI. In my project, I included "@angular/material": "^8.2.3" and "bootstrap": "4.3.1". For styling purposes, I imported various Bootstrap SCSS files into my style.scss file. @import "~bootstrap/sc ...

Utilize the hexadecimal color code as a string within the darken function

When working with a less style, I have a string variable. @colorString: 'DADADA'; I can convert it into a color: @color: ~'#@{colorString}'; Then, I am able to use @color to define a value in a style: div { color: @color } However ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Individual file for storing strings related to HTML content

Is there a method for organizing all constants in HTML (such as strings and numbers) into a separate file? Instead of <title>Hello World</title> could we do something like this instead? <title>STR_TITLE</title> and then, in ano ...

Element Not Found Error: Element could not be located - Script using JavaScript with Seleniumwebdriver

After extensive research, I have identified the issue at hand. The challenge lies in the fact that others do not follow the same coding structure as me and are unclear about where or what to insert into my code. I am aware that a try/catch statement or t ...

Switching back and forth between two CSS animations using Jquery

I am working on creating a unique pendulum system using 3 balls. After successfully creating the balls and animating them, I am faced with a challenge in making the animation continuous. Here is my code: .circle { width:30px; height:30px; backgrou ...

Utilizing data attributes and JavaScript to dynamically assign a class to carousel navigation items

Hello there! I recently created a carousel and carousel navigation system using Bootstrap. I am now trying to figure out how to detect the value of 'data-slide-to' and then apply a specific style to the corresponding navigation item based on that ...

What is the best way to ensure that my text and clickable URLs can be effectively sent through a Teams chat webhook without any truncation issues?

My ultimate aim is to achieve in Teams what can easily be accomplished with Slack Webhooks, like this: await fetch(slackWebhook, { method: 'POST', headers: { 'Content-Type': 'application/json' ...

Using PHP and jQuery to showcase files found within a directory

My goal is to use a combination of PHP and jQuery to display files stored in a specific directory. I have integrated Datatables to present all the records from a database, some of which have files associated with them. Users can click a link to open a moda ...

Hovering over the top menu items in AngularJS will reveal dropdown submenus that will remain visible even when moving the cursor

I am facing an issue where my top menu has links that display a dropdown of additional menu items upon hovering. I have attempted to use onmouseover and onmouseleave events to control the visibility of the sub menu. However, I have encountered a problem ...

Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep ...

Displaying contents do not seem to work with the background color

I've been attempting to include a border and background-color to my table but for some reason it's not taking effect. This is the CSS code for my table: table { width: 100%; display: grid; overflow: auto; } table thead, table tbody, t ...

Modify the style of a newly created div by clicking on it

Exploring vue-cli and encountering a challenge. I've created a row of 24 div elements with the following code: <template> <div class="row"> <div class="hour" v-on:click="colorize" v-for="n in 24"></div> </div&g ...

Background image not adhering to the page width as expected within the Bootstrap framework

I feel like I'm losing my mind. Currently, I am in the process of designing a section that consists of four photo boxes - two at the top and two below. In order to achieve this layout, I have turned to utilizing Bootstrap. Unfortunately, this parti ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

Partial views within a nested hierarchy are not updating as expected

I am currently working on a partial view that has the following structure: @model ComPost.Core.CommandsAndQueries.Contract.DataContract.FinalizeScreenDTO <div class="row"> <p> <table id="ProductTable"> <tr><td> ...

What methods can I use to prevent multiple calls to isValid in this particular jQuery validation scenario?

I am currently working on validating a field with the following requirements: No validation when the user first lands on the page Validation triggers when the user clicks on the Name Query field, and it validates on both key up and focus out events The f ...