I have a problem with validation on radiobutton.
I did try by having a loop to check if the radiobutton is checked or not but it turns out give delivery flag still true
var optDelivery=document.getElementsByName("f__deliver");
var deliveryFlag=false;
for (var i=0;i<optDelivery.length;i ){
if (optDelivery.checked){
deliveryFlag=true;
}
}
if (deliveryFlag===true){
alert("AAAA");
optDelivery.style.background="white";
optDelivery.style.color="#000";
} else{
alert("A");
optDelivery.style.background="#DE8971";
optDelivery.style.color="#FFE9D6";
optDelivery.focus();
return false;
}
CodePudding user response:
You need to access each input radio by its index, also the condition needs to be inside the loop
Also instead of return false
set deliveryFlag
to false
const optDelivery = document.getElementsByName("f__deliver");
let deliveryFlag = false;
for (let i = 0; i < optDelivery.length; i ) {
if (optDelivery[i].checked) {
deliveryFlag = true;
}
if (deliveryFlag === true) {
console.log("AAAA");
optDelivery[i].style.background = "white";
optDelivery[i].style.color = "#000";
} else {
console.log("A");
optDelivery[i].style.background = "#DE8971";
optDelivery[i].style.color = "#FFE9D6";
optDelivery[i].focus();
}
deliveryFlag = false;
}
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="" checked>
<input type="radio" name="f__deliver" id="">
CodePudding user response:
var optDelivery=document.getElementsByName("f__deliver");
var deliveryFlag=false;
for (var i=0;i<optDelivery.length;i ){
if (optDelivery[i].checked){
deliveryFlag=true;
}
if (deliveryFlag===true){
alert("AAAA");
optDelivery[i].style.backgroundColor="white";
optDelivery[i].style.color="#000";
optDelivery[i].focus();
}else{
alert("A");
optDelivery[i].style.backgroundColor="#DE8971";
optDelivery[i].style.color="#FFE9D6";
}
deliveryFlag = false;
}
<input type='radio' name = 'f__deliver'>
<input type='radio' name = 'f__deliver' checked>
<input type='radio' name = 'f__deliver'>