Search code examples
spring-bootthymeleaf

Pass a List to Javascript function in Thymeleaf


I have seen several examples of sending individual parameters to a JavaScript function, but not a List.

When I try to pass a list, it comes to function as a big string. This is what I have:

<select id="namespace" name="namespace"
        th:responseList="${responseList}"
        th:onchange="javascript:print(this.getAttribute('responseList'));">
        <option value="">Select Source Namespace</option>
        <option th:each="item : ${responseList}"
            th:value="${item.namespace}"
            th:text="${item.namespace}"></option>
</select>

function print(responseList) {
    console.log(responseList);
}

Solution

  • Try this

    <script th:inline="javascript">
        var list = [[${responseList}]]; 
        console.log(list );
    </script>
    

    Hope work for you