I'm facing an issue where I need to conditionally assign an attribute to each item in an array based on a radio button value. I have been able to set the required attribute on individual items, but I'm struggling to apply it to all elements in the array at once. I have tried using forEach() but I keep getting an error message saying "item.setAttribute is not a function". My JavaScript skills are not the strongest, so I'm sure there's a simple solution that I'm overlooking.
Here is what I have attempted so far: within the forEach(function(item, i) { item.setAttribute('required', 'true'); } - which is throwing an error stating "item.setAttribute is not a function"
//assign required fields to a variable
const reqCollection = [document.getElementsByClassName("reqcheck")];
console.log(reqCollection);
document.addEventListener('DOMContentLoaded', () => {
// on .conditional_radio-wrapper click
document.querySelectorAll('.conditional_radio-wrapper').forEach(trigger => {
trigger.addEventListener('click', function() {
//assign variable for "Are you a realtor?"
let realtorRadio = document.querySelector('input[name="realtorChoice"]:checked').value;
//log realtorRadio
console.log(realtorRadio);
//assign variable for "Are you represented by a realtor?"
let repRadio = document.querySelector('input[name="realtorRep"]:checked').value;
console.log(repRadio);
//assign required fields to a variable
//if they are a realtor or represented by one
if (realtorRadio == "Yes" || repRadio == "Yes") {
reqCollection.forEach(function (item, i) {
//works
item[0].setAttribute('required', 'true');
item[1].setAttribute('required', 'true');
item[2].setAttribute('required', 'true');
//does not work
item.setAttribute('required', 'true');
});
}
//else mark as not required
else {
reqCollection.forEach(function (item, i) {
item[0].removeAttribute('required');
item[1].removeAttribute('required');
item[2].removeAttribute('required');
});
}
});
});
});