How to customize the background color in a Thymeleaf select element

Here is the HTML code I am working with:

<select  
        th:field="*{status.health}" 
        th:value="${status.health}"
        th:class="health_color"                                 
        th:name="status_health">
    <option value="-1">Select Health</option>
    <option th:class="health_color" th:value="green" th:text="green"></option>
    <option th:class="health_color" th:value="yellow" th:text="yellow"></option>
    <option th:class="health_color" th:value="red" th:text="red"></option>
</select>

Additionally, I have included the following JavaScript snippet:

$('.health_color').each(function() {
    if ($(this).text() == 'red') {
        $(this).css('background-color', '#ff5050');
    } else if ($(this).text() == 'yellow') {
        $(this).css('background-color', '#ffd24d')
    } else if ($(this).text() == 'green') {
        $(this).css('background-color', '#80ffaa')
    }
});

All elements on the page are styled correctly except for the select box itself. Can someone please advise on how to rectify this issue?

Thank you.

Answer №1

It seems like the function is looking for color information from a text property, which is not present in the select field.

My assumption is that when $(this).text() is executed on the select, it retrieves the concatenated text properties within.

Below is a code snippet where I test this theory.

Don't forget that you can utilize Chrome Developer Tools (for example) to debug your code and gain further insight into its behavior

$('.health_color').each(function() {
    console.log($(this).text());
    if ($(this).text() == 'red') {
        $(this).css('background-color', '#ff5050');
    } else if ($(this).text() == 'yellow') {
        $(this).css('background-color', '#ffd24d')
    } else if ($(this).text() == 'green') {
        $(this).css('background-color', '#80ffaa')
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="health_color"
        name="status_health">
    <option value="-1">Select Health</option>
    <option class="health_color" value="green" text="green">green</option>
    <option class="health_color" value="yellow" text="yellow">yellow</option>
    <option class="health_color" value="red" text="red">red</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

Tips for retaining white spaces and line breaks when adding text with jQuery append

When submitting a textarea using ajax and appending the response to a class, it only shows the content when there is no new line in the text area. Here is the HTML: <p id="updateres_n"></p> <div class="update_res"></div> Be ...

Django Accordion Table Template

I have a Django model that populates a table with objects from a database. What I'm trying to achieve is, when a row in the table is clicked, to use JS or JQuery to accordion a table of objects that are connected as foreign keys to the main object. A ...

What are the steps to implement jQuery in Internet Explorer 9?

Can anyone explain why this code snippet is not functioning properly in IE9? Check it out here: http://jsfiddle.net/S7ERu/1/ //jquery $("#submitpost").on("click", function () { alert('test'); }); //html <a href="#" id="submitpost"&g ...

Slideshow box with images aligned perfectly

I have designed a container with images, but my goal is to: either show the images inline or stack them on top of each other, and then be able to navigate through them using jQuery. I attempted absolute positioning on both .box and .box img, as well as u ...

Unable to locate and interact with element using CSS Selector in the webdriver

I am having trouble locating the element that contains both "Confirm" and "Cancel" without using Xpath. Can anyone suggest a better approach to find this element? Below is the HTML code snippet: <div class="ui-dialog-buttonpane ui-widget-content ui- ...

I'm having trouble centering the links in my navigation bar using flexbox, and I'm not sure how to fix it

Struggling with creating a navigation bar for my portfolio-building project. The "Who needs a quote" element is correctly displaying on the left, but I can't figure out how to center align the links "Sports, business, politics". Tried using flexbox op ...

Align the text in the center of the button vertically

Struggling to vertically center text on a button? I understand the frustration! I've been working on this issue for a whole day with no success. My setup involves NEXT.js and TailwindCSS. <main> <div class='flex justify-center ite ...

Incorporating a scroll bar into a horizontal display

In troubleshooting this web interface, I encountered an issue related to the horizontal view. The problem is evident in the image below - when in horizontal view, more vertical space is required, prompting the need for a scrollbar to be added between the ...

How can I align text to the center and set the text color at the same

Looking to place text in the center of a colored box? Although attempting to center the text, you may find that it remains towards the top rather than in the middle of the box. How can you shift the text down so it aligns with the middle of the backgroun ...

I am looking to create a rounded circular progress bar with smooth edges

I'm looking to create a circular progress bar with rounded edges on the highlighted segment, similar to this example: https://i.sstatic.net/kNKyzm.png While I've managed to create a basic version, I'm struggling to achieve the rounded ends ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Choosing a sibling element before another using CSS

Is there a way to make both of my icons display some text when hovered over? I managed to make it work, but the leftmost icon doesn't trigger the span element when hovered. The text needs to appear on the left side of the Yelp icon for design reasons. ...

Unable to show the list of comments with jQuery functionality

Having trouble with my code to display the comment list correctly. I can't seem to get the expected result, could you please review it and help me find the mistake. The current output is as follows: var item = $('<div>'); $.each(d ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

ToggleClass is not being applied to every single div

I am currently designing a pricing table with hover effects. You can view the progress here: Upon hovering on a pricing table, all the divs are toggling classes which is not the desired behavior. I want each element to have its own separate interaction. ...

Ensuring W3C compliance with form elements on the server-side

After running a website HTML validation on w3.org, I encountered the following error: Bad value for the attribute 'action' on the form element: It must be non-empty. My form is an ASP.NET server-side form and I am unable to set the 'acti ...

Take the information entered in an HTML form, add it to a JSON object, and save it in a MYSQL

I'm currently working on extracting data from a user registration form in HTML, converting it to JSON format, and then storing it in MySQL. Your assistance with this process would be greatly appreciated. HTML <form id="myForm" action="userInf ...

Creating an accessible order for the next and back buttons

Currently, I am working on designing the user interface for a checkout flow. Towards the end of the page, there are 3 buttons available - Next, Back, and Cancel. When viewed on a desktop, the button layout appears as follows: (Back) (Next) Cancel http ...

Experience the magic of CSS Sprite once it's been successfully uploaded!

Visit the website for testing here Located at the bottom of the page are two images with hover effects - one labeled "Contact us" and the other "Jobs Available!" During local testing, these images are visible. However, once uploaded to a server, they dis ...

Navigate through content to reach the bottom of the webpage

I am currently working on a layout that is similar to Facebook's messaging system (facebook.com/messages). I have made some progress with it, but not quite there yet. You can view my work so far here: https://jsfiddle.net/3nd0b17m/23/ https://i.sstati ...