我有以下由两个单选按钮组成的 HTML 代码。我需要如果用户选择一个,取决于它是,“折扣百分比”字段是否处于活动状态。
<div class="form-group">
<label for="isProductDiscounted" class="text-uppercase font-weight-bold">Is Product Discounted?</label>
<div class="btn-group w-100" data-toggle="buttons" name="isProductDiscounted">
<label class="btn btn btn-blue-grey waves-effect w-50 form-check-label active">
<input id="isDiscounted" class="form-check-input" name="isDiscounted" type="radio" value= 0 th:field="*{discounted}" autocomplete="off" checked> No discounted
</label>
<label class="btn btn btn-blue-grey waves-effect form-check-label w-50">
<input id="isNotDiscounted" class="form-check-input" name="isDiscounted" type="radio" value= 1 th:field="*{discounted}"> Discounted
</label>
</div>
</div>
<div class="form-group">
<label for="discountPercentage" class="text-uppercase font-weight-bold">Discount Percentage</label>
<input type="number" class="form-control" id="discountPercentage" th:field="*{discountPercentage}">
<small class="form-text text-danger" th:if="${#fields.hasErrors('discountPercentage')}" th:errors="*{discountPercentage}"></small>
</div>
默认情况下,加载页面时,选中的单选按钮为“无折扣”。我尝试了以下代码,但它根本不起作用,因为无论选择的单选按钮如何,输入总是被禁用。
var discounted = document.getElementById('isDiscounted');
var no_discounted = document.getElementById('isNotDiscounted')
var discount_percentage = document.getElementById('discountPercentage')
if(discounted.checked) {
discount_percentage.disabled = true;
} else {
discount_percentage.disabled = false;
}
提前致谢。
问题是您没有监听单选按钮中的更改,将所有内容封装在一个函数中并向两者添加监听器,以便每次单击其中一个时它们都可以更改状态
代码如下所示: