Home > Blockchain >  Use javascript function in th:if for filtering some table entities
Use javascript function in th:if for filtering some table entities

Time:12-19

I want to hide the table rows that do not satisfy a date condition written in javascript function.

the th:onclick attribute is working fine and returns me the correct comparison. But when I run the same in th:if the function is not called!

the syntax for the function call:

case 1: the function is called and returns me the true or false

<tr th:each="patient : ${patients}"  th:onclick="compareDates([[${patient.dateConverter()}]])">

case 2 that I want to use for the table row filtering: the function is not called:

<tr th:each="patient : ${patients}"  th:if="compareDates([[${patient.dateConverter()}]])">

the js function is as follows:

<script th:inline="javascript">
/*<![CDATA[*/
    
     function compareDates(date) {
     
    var date1= document.getElementById("appDate").valueAsDate.toLocaleDateString();

    return date == date1;
}
/*]]>*/
</script>

I tried to use th:hidden attribute as well I am getting the following error:

Caused by: org.attoparser.ParseException: Could not parse as expression: "compareDates([[${patient.dateConverter()}]])" (template: "index" - line 277, col 50)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 121 more

CodePudding user response:

For those having the same challenge, I implemented the table filtering by pure javascript after thymeleaf generated the table. The js function is as follows:

function compareDates() {
         var rows = document.getElementsByTagName("table")[0].rows;
         for (let i = 1; i < rows.length; i  ) {
             var td = rows[i].getElementsByTagName("td")[2];
             var split= td.innerHTML.split(" "); 
             
           if(split[0]!= document.getElementById("appDate").valueAsDate.toLocaleDateString()){
             
               rows[i].style.display = "none";
           }
           else {
               rows[i].style.display = "table-row";
           }
         }
}

references:

Hiding a <td> depending on the Condition

how to get a td value of a table using javascript

  • Related