I'm using Bootstrap 4 and designing a mock item submission form in my web app. In the transaction row, the text input for price is default disabled. What should I do if I enable the text input after clicking the 'sell' button?
<div class="form-inline">
<div class="form-group">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="free" name="customRadioInline1" class="custom-control-input" checked>
<label class="custom-control-label" for="free">Free</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="sell" name="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="sell">Sell</label>
</div>
</div>
<label for="price">Price</label>
<input type="text" class="form-control" id="price" placeholder="HKD" disabled>
</div>
I expect there will be some code which includes 'onclick' and 'add.eventListener' on the 'sell' radio button when writing JS, but I don't know how to code so that enabling typing the price after selecting the sell button, and keeping disabled when default (i.e. free).
Or, is there any easy way with Bootstrap 4?
Thank you for your help.
You can first target all the radios with Document.querySelectorAll()
. Then loop through them with forEach()
to attach the event (click). Inside the event handler function you can check the id of the clicked radio button based on which you can set/remove the attribute (disabled
).
Try following way:
var radios = document.querySelectorAll('[name=customRadioInline1]');
Array.from(radios).forEach(function(r){
r.addEventListener('click', function(){
var priceEl = document.getElementById('price');
if(this.id == 'sell')
priceEl.removeAttribute('disabled');
else
priceEl.setAttribute('disabled', 'disabled');
});
});
<div class="form-inline">
<div class="form-group">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="free" name="customRadioInline1" class="custom-control-input" checked>
<label class="custom-control-label" for="free">Free</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="sell" name="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="sell">Sell</label>
</div>
</div>
<label for="price">Price</label>
<input type="text" class="form-control" id="price" placeholder="HKD" disabled>
</div>