Reputation: 161
My radio button checking is not working. Can anyone please help me with this? I want to check if the radio button is checked or not. if not checked then I want this program to give an alert. But in this program whenever the radio button is not checked I am not getting the alert.
<div>
<label for="gender">Gender: </label>
<input type="radio" name="myRadio"> Male
<input type="radio" name="myRadio"> Female
<input type="radio" name="myRadio"> Other
</div>
The radio button checking function is given below:
function radioCheck(){
var radio = document.forms["myForm"]["myRadio"].value;
for (var i=0; i<radio.length; i++) {
if (radio[i].checked){
break;
}else
{
alert("No radio button is checked");
}
}
}
Upvotes: 0
Views: 502
Reputation: 1736
Okay so this is working code:
function radioCheck(){
const radioList = document.getElementsByName("myRadio")
let notChecked = false;
for(let i = 0; i < radioList.length; i ++){
if(radioList[i].checked){
return;
} else {
notChecked = true;
}
}
if(notChecked){
alert("No radio button is checked")
}
}
radioCheck()
To explain:
document.getElementsByName
because the only one thing that they have the same is name
property which is name="myRadio"
in this examplenotChecked
which is false on initial so when it will go through all inputs and see that one of them is not selected if will show alertnotChecked = true
notChecked
value is true and if it is it shows an alertradioCheck()
in the end<button onclick={radioCheck()} > run again </button>
so after clicking on button "run again"
you can use it again (just for test)
here is working example:
hope that my answer will help you out :) if you have any questions please ask
Upvotes: 1