Here is the form I have ( many dishes where each has an input number ( quantity of dishes to order ).
The problem is that I would like to show the price of an order before the order is done, for this I need to sum somehow input of the ${dish.price}
, but how can this be done?
<form action="#" th:action="@{/menu}" th:object="${order}" method="post"> <div th:each="dish : ${dishList}"> <div> <h4 th:inline="text">[[${dish.name}]]<span class="price" th:text="${dish.price}">45</span></h4> <p th:text="${dish.category}">DRINKS</p> <p th:text="${dish.description}"> Aperiam tempore sit,perferendis numquam repudiandae porro voluptate dicta saepe facilis. </p> <div> <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button> <input th:value="0" th:name="${'dishIdQuantityMap[' + dish.id + ']'}" type="number" min="0" max="100" step="1" /> <button class="increment" type="button" onclick="stepperIncrement(this)">+</button> </div> </div> </div> </div> <button type="submit" value="Submit">Confirm order</button> </form>
JS ( Just inputs +1 to input type"number"
when the button is clicked )
function stepperDecrement(btn){ const inputEl = btn.nextElementSibling; const calcStep =inputEl.step * -1; const newValue = parseInt(inputEl.value) + calcStep; if(newValue >= inputEl.min && newValue <= inputEl.max){ inputEl.value = newValue; } } function stepperIncrement(btn){ const inputEl = btn.previousElementSibling; const calcStep = inputEl.step * 1; const newValue = parseInt(inputEl.value) + calcStep; if(newValue >= inputEl.min && newValue <= inputEl.max){ inputEl.value = newValue; } }
Advertisement
Answer
Of course yes, it is possible.
To get server data inside your thymeleaf templates, you can proceed various ways, and it depends on the context where you need that data.
Inside Javascript, (CSP “script-src ‘unsafe-inline’ …” or <script th:inline="javascript" nonce="" ...>
are required because writing JS inline is a bad way regarding all XSS caveats. Thanks OWASP), you can try to write : let productCategory = /*[[${productCategory}]]*/ '';
Inside Javascript with ES6+ modules (with webpack or any other solution), you can check an endpoint of your webapp (using Promise feature with polyfill) which will load data inside a form input element. And make your operations as usual. Have fun.