Search code examples
htmlcssthymeleaf

thymeleaf select backgound color


I have the following HTML:

<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>

And the following JavaScript

$('.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')
    }
});

The styles above show up in all the other elements of the page, including the select options, but not the select box itself. What am I doing wrong?

Thanks.


Solution

  • I believe that the function is expecting to read the color from a text property, which the select field doesn't have.

    My best guess is that when $(this).text() run for the select, it returns the combined properties of all the text properties inside.

    Below is a code snippet testing my theory.

    Remember that you can always debug your code using chrome developer tools (for instance), it may give you a better insight on what's going on with it.

    $('.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>