Issue
I cannot figure out how to get this Thymeleaf code to work properly. I am recieving an unexpected identifier for the th:onclick function:
th:onclick="'addBadge('badgeListTwy', \'' + ${taxiway.getId()} + '\', \'' + ${taxiway.getName()} + '\');'"
This is part of a drop down list that I'm trying to populate for a button using th:each
<ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<li th:each="taxiway : ${taxiways}">
<a class="dropdown-item" href="#" th:onclick="'addBadge('badgeListTwy', \'' + ${taxiway.getId()} + '\', \'' + ${taxiway.getName()} + '\');'"><span th:text="${taxiway.getName()}"></span></a>
</li>
</ul>
This gives me an 'Uncaught SyntaxError: Unexpected identifier' error
Solution
The best way to do this is to store arguments in data attributes, like this:
<ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<li th:each="taxiway : ${taxiways}">
<a class="dropdown-item" href="#"
th:data-id="${taxiway.id}"
th:data-name="${taxiway.name}"
onclick="addBadge('badgeListTwy', this.getAttribute('data-id'), this.getAttribute('data-name'));"><span th:text="${taxiway.getName()}"></span></a>
</li>
</ul>
It simplifies the quoting, and removes certain JavaScript vulnerabilities. (Notice I'm using onclick
instead of th:onclick
.)
That being said the original expression probably isn't working becuase you didn't escape the quotes around 'badgeListTwy'
Answered By - Metroids