I’m working on a Spring Boot + Thymeleaf project in which I have an order form. In that form, there is a dropdown for choosing a product, and I want the product’s price to automatically appear in the Net Unit Price input field right after the user selects an item from the dropdown.
I tried to store each product’s price in a data-price attribute on the elements, then used JavaScript to listen for a change event on the dropdown, grab the selected element’s data-price, and set that value in the input. However, no matter what I do, the Net Unit Price field remains blank. I even tested with plain HTML + JS, but it still doesn’t update in the live environment.
Here’s the relevant part of my Thymeleaf template:
<select id="productSelect"
th:field="*{product.id}"
class="form-select"
required>
<option disabled selected value="">Select</option>
<option th:each="p : ${products}"
th:value="${p.id}"
th:attr="data-price=${p.price}"
th:text="${p.name}">
</option>
</select>
<input type="number"
step="0.01"
th:field="*{netUnitPrice}"
class="form-control"
id="netUnitPrice"
required />
<script>
document.addEventListener('DOMContentLoaded', function() {
const productSelect = document.getElementById('productSelect');
const netPriceInput = document.getElementById('netUnitPrice');
productSelect.addEventListener('change', function() {
const selectedOption = this.options[this.selectedIndex];
const price = selectedOption.getAttribute('data-price');
if (price) {
netPriceInput.value = price;
}
});
});
</script>
I also have a base.html layout that loads Bootstrap and other scripts. I worried maybe it conflicts with my inline script, but I haven’t found a direct conflict. Right now, the JavaScript doesn’t throw any errors in the console, and the data-price attributes look correct in the rendered HTML, but the input never updates.
Any ideas on what I might be missing or doing wrong? Let me know if you need more details about the layout or the form. Thank you so much in advance!