I have tried to create a section of a form which is disable if user choose A and accessible if user choose B.
document.getElementById('delivery').onclick = function() {
var disabled = document.querySelectorAll(".disabled").disabled;
if (disabled) {
document.querySelectorAll(".disabled").disabled = false;
}
else {
document.querySelectorAll(".disabled").disabled = true;
}
}
<!--The toggle button-->
<div class="radio-choice">
<input type="radio" name="pickup-delivery" id="pickup" value="pickup">Pick-up</input>
<input type="radio" name="pickup-delivery" id="delivery" value="delivery">Delivery</input>
</div>
<!--The part that should be disable if user choose pick-up method-->
<label for="street_address" class="delivery-label disabled-label">Street Address:</label>
<input type="text" id="street_address" class="disabled" name="street_address" disabled>
<label for="city" class="delivery-label disabled-label">City:</label>
<input type="text" id="city" class="disabled" name="city" disabled>
<label for="zip_code" class="delivery-label disabled-label">Zip Code:</label>
<input type="text" id="zip_code" class="disabled" name="zip_code" disabled>
What is really weird is that this code works with QuerySelector, but ofc only for one element, but not QuerySelectorAll.
I am just using Javascript and not JQuery as I have just started coding and don’t master libraries.
Thanks in advance for your help.
>Solution :
As mentioned, you should loop over the node list. You should also avoid using var as it’s bad practice. I would also suggest some changes to your code to make it a bit more readable:
const disabled = document.querySelectorAll('.disabled')
document.querySelectorAll('input[name="pickup-delivery"]').forEach((elem) => {
elem.addEventListener("click", function(e) {
const item = e.target.value;
if(item==="pickup") {
disabled.forEach(e=>{e.disabled = true})
}else{
disabled.forEach(e=>{e.disabled = false})
}
});
});