Reputation: 355
I stumbled upon a problem that i have no idea how to fix. I want to be able to check when a radio button is checked. If one of the five buttons is checked, it should give the feedback. Somehow with my code, when i check the first radio button, it works. But if i check the 2nd or 3rd ... It gives me the alert message: please give a rating. So that means either the for loop in the function radioChecker is not working as intended, or i don't know.
{
let validation = document.querySelector('.type__style');
let validation2 = document.getElementById("label__text");
const init = () => {
const $button = document.getElementById('send__button');
$button.onclick = () => {
revealText();
setTimeout(dissapearText, 4000);
}
const radioChecker = () => {
let radios = document.querySelector(".stars").querySelectorAll("input");
for (let i = 0; i <radios.length; i++) {
if (radios[i].checked) {
console.log("yes");
return true;
} else {
return false;
}
}
}
const revealText = () => {
if (validation.value === "") {
validation.focus();
window.alert("Please enter your name.");
return false;
} else if (validation2.value === "") {
validation2.focus();
window.alert("Please fill in commentary.");
return false;
} else if (radioChecker() === false) {
window.alert("Please give a rating.");
return false;
} else {
document.querySelector('.feedback').style.opacity = 1;
console.log('work');
return true;
}
}
const dissapearText = () => {
document.querySelector('.feedback').style.opacity = 0;
}
}
init();
}
Upvotes: 1
Views: 2151
Reputation: 3223
const radioChecker = () => {
let radios = document.querySelector(".stars").querySelectorAll("input");
for (let i = 0; i <radios.length; i++) {
if (radios[i].checked) {
console.log("yes");
return true;
}
}
return false;
}
Explanation:
So, the for loop check all radios
. if any radio is checked, it will immediately return true
.
After running full loop, if it did not find any radio is checked, it will return false
.
Upvotes: 1
Reputation: 791
This is because you have a return true
in the loop. The moment it returns true on the first loop it will break the loop.
Upvotes: 2