<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也有一个base.html布局,该布局加载了引导程序和其他脚本。我担心它可能与我的内联脚本相抵触,但我没有发现直接的冲突。目前,JavaScript不会在控制台上丢弃任何错误,并且数据价格属性在渲染的HTML中看起来正确,但是输入永远不会更新。
关于我可能会想念或做错事的任何想法?让我知道您是否需要有关布局或表格的更多详细信息。非常感谢您!
当代码或多或少地运行代码时,它可以正常工作。如果您可以提供更多调试信息,我想扩展答案。
<select id="productSelect" th:field="*{product.id}" class="form-select" required>
<option disabled selected value="">Select</option>
<option value="1" data-price="12">Product 1</option>
<option value="2" data-price="17.85">Product 2</option>
<option value="3" data-price="6.25">Product 3</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>