Search code examples
javascriptarraysspring-bootspring-mvcthymeleaf

Thymeleaf: How can I search an array with a variable index?


How can I use a variable as index of an array, accessed through Thymeleaf in HTML with a JavaScript function?

In this case, I want to use gcounter as a variable index for the array tlist

The input works fine.

This [[${tlist[1].id}]] works fine too.

But I need a variable index.

Any ideas?

Edit: My problem is pretty much similar to this: Struts2 Access specific index of list when index is a variable

    <form>
           <div>
               <input  id="favoriteInput" maxlength="3" name="favNummer" required type="number"/>
               <input onClick="saveFavorit();" type="Submit"/>
               <script th:inline="javascript">
             function saveFavorit() {
                 var counter = document.getElementById("favoriteInput").value
                 var gcounter = Number(counter);

                 var idz = [[${tlist[(var gcounter;)].id}]];
                   "; path=/";

                 document.cookie = "id=" + idz +"; expires=" + "Fri, 31 Dec 9999 23:59:59 GMT"+"; path=/";

             }
               </script>
           </div>
       </form>

Solution

  • You can do this by breaking your single step [[${tlist[index].id}]] into two steps:

    1) Populate the JS variable (the data array) from Thymeleaf.

    2) Use the value provided in the input field to access the required array entry.

    Assuming you have a Java array of User objects, similar to the following, with a user ID and a user name...

    User user1 = new User(123, "Bob");
    User user2 = new User(124, "Anne");
    User user3 = new User(125, "Jane");
    User[] users = { user1, user2, user3 };
    

    ...and you have an input field in your template similar to this:

    <div>
        <input id="favoriteInput" 
               maxlength="3" 
               name="favNummer" 
               required type="number"
               onClick="saveFavorit();"/>
    </div>
    

    ...then you can include a script similar to the following:

    <script th:inline="javascript">
      function saveFavorit() {
        var index = document.getElementById("favoriteInput").value;
        var usersArray = [[${users}]];
        if (index >= 0 && index <= usersArray.length - 1) {
          var selectedUserName = usersArray[index].userName;
        }
        console.log(selectedUserName);
      }
    </script>
    

    This will print out the user name (to the browser's console) corresponding to the index number in the input field. A value of "0" will print "Bob", and so on.

    Because Thymeleaf is processed on the server side, it has no knowledge of the values entered by the user into the input field, on the web page.