I'm trying to assign an attribute to every item in an array conditionally based on a radio value. I've gotten all the way up to actually setting the required attribute but for some reason, I can only set it on items individually, not to every element called in my array. I'm sure there's something I'm doing that's sticking out like a sore thumb but javascript is not my forté.
What I've tried: inside the forEach(function (item, i){item.setAttribute('required','true'}; - which returns "item.setAttribute is not a function"
//assign required fields to 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 variable
//if they are a realtor or represented by one
if (realtorRadio == "Yes" || repRadio == "Yes") {
reqCollection.forEach(function (item, i) {
//does work
item[0].setAttribute('required', 'true');
item[1].setAttribute('required', 'true');
item[2].setAttribute('required', 'true');
//doesn't 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');
});
}
});
});
});
CodePudding user response:
This line is problematic:
const reqCollection = [document.getElementsByClassName("reqcheck")];
You're getting an HTML collection array and encapsulating it in another array.
I would recommend just this:
const reqCollection = document.querySelectorAll(".reqcheck");
Then you can just iterate through
reqCollection.forEach(item => item.setAttribute('required', 'true'));
CodePudding user response:
With your implementation the reqCollection
variable is an array with just one element which is a HTMLCollection
returned from getElementsByClassName
, you need to spread the elements inside the array by spread operator on the document.getElementsByClassName("reqcheck")
const reqCollection = [...document.getElementsByClassName("reqcheck")];