Avatar of Aleks
Aleks
Flag for United States of America asked on

Select one javascript for radio buttons

I have the javascript below to make sure a user checks at least one checkbox.
Seems to work fine for checkboxes but not for radio buttons. I need help tweaking it so that it works.

I have a repeated region displaying names, they all have ids, I need the user to select one of the radio buttons.

<script language="JavaScript">
function oneCheckboxChecked(form){
for(f=0;f<form.length;f++){
if(form[f].type !="checkbox") continue;
if(form[f].checked){
return true;
}
}
alert("Select at least one User");{
return false;
}
}
</script>

Open in new window


A
JavaScriptWeb Development

Avatar of undefined
Last Comment
Rajar Ahmed

8/22/2022 - Mon
Rajar Ahmed

Try this,
<script language="JavaScript">
function oneCheckboxChecked(form){
for(f=0;f<form.length;f++){
if(form[f].type =="radio") 
if(form[f].checked){
return true;
}
}
alert("Select at least one User");
return false;
}
</script>

<form id="form1">
<input type="radio" name="gender" value="male" > Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other

<input type="button" name="button" value="Click" onclick="oneCheckboxChecked(document.getElementById('form1'))"> <br>
</form>

Open in new window

Aleks

ASKER
Can I apply it to onsubmit for the form instead ?
ASKER CERTIFIED SOLUTION
Rajar Ahmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck