I have the following HTML code which consists of two Radio Buttons. I need that if the user chooses one, depending on which it is, the "Discount Percentage" field is active or not.
<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>
By default, when loading the page the selected radio button is "No discounted". I have tried the following code, but it doesn't work at all, since the input is always disabled regardless of the selected radio button.
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;
}
Thanks in advance.
The problem is that you are not listening to the changes in the radio buttons, encapsulate everything in a function and add listeners to both so that they can change the state every time you click on one of them
The code would look like this: