Search code examples
javascripthtmlthymeleaf

Thymeleaf javascript replacing an image source based on text in table


this is my first post. I have been trying to look for an answer that but I can't find one.

I am trying to replace an image source in my HTML dependent on text displayed in the {td.status}, for example "SUBMITTED"

My HTML :

<table id = "myTable">
    <tbody>
    <tr>
        <th>Reference</th>
        <th>Version</th>
        <th>Last Modified</th>
        <th>Status</th>
    </tr>

        <tr th:each="td: ${thedata}">


            <td><span th:text="${td.thedataPrimaryKey.ref}"></span></td>
            <td><span th:text="${td.thedataPrimaryKey.version}"></span></td>
            <td><span th:text="${td.thedataTimestamp}"></span></td>

            <td><span><img class="myImage" th:src="@{/assets/images/offbulb.png}" style="width:15px; height:10px"; /></span><span th:text="${td.status}"></span></td>


    </tbody>
</table>

My JS :

function f_color(){

    table = document.getElementById("myTable");

    if (table.getElementsByTagName('TD')[3].value == 'SUBMITTED') {

        var image = document.getElementsByClassName("myImage");

        image.src = "@{/assets/images/redbulb.png}";
    }
}

As it stands, my blank lightbulb is showing, but not being replaced. I managed to do something similar with changing font colors previous to this but I am aiming to upgrade that with better visuals, unfortunately I am struggling and any help will be appreciated.


Solution

  • Do you need to do it in JavaScript? I think this should be done in Thymeleaf, myself.

    <td>
      <img th:if="${td.status != 'SUBMITTED'}" class="myImage" th:src="@{/assets/images/offbulb.png}" style="width:15px; height:10px"; />
      <img th:if="${td.status == 'SUBMITTED'}" class="myImage" th:src="@{/assets/images/redbulb.png}" style="width:15px; height:10px"; />
      <span th:text="${td.status}" />
    </td>