Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking for checked radio buttons 1

Status
Not open for further replies.

smashing

Programmer
Oct 15, 2002
170
0
0
US
I know that the following works very well:

<script LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
<!-- Hide script from older browsers
function validForm(ContactForm) {
for(j=0;j< ContactForm.plan_id.length;j++) {
el = ContactForm.plan_id[j];
if(el.checked == true){
return true;}}
alert("Please choose a plan type");
ContactForm.plan_id[0].focus();
return false
}// End hiding script --></script>


But since I am validating other stuff as well and the return true & return false are reversed as is standard code (see below) as is standard, but now I cannot get the radio check part right. It is alerting me in all cases whether checked or not.

<script LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
<!-- Hide script from older browsers
function validForm(ContactForm) {
if (ContactForm.rent_fname.value =="") {
alert("Please enter the renter's first name")
ContactForm.rent_fname.focus()
return false
}
if (ContactForm.phone_id.value =="99") {
alert("Please choose the phone you want to assign")
ContactForm.phone_id.focus()
return false
}

for(j=0;j<ContactForm.plan_id.length;j++) {
el = ContactForm.plan_id[j];
if(el.checked != true){
alert("Please choose a plan type");
ContactForm.plan_id[0].focus();
return false
}
}
return true
}



Note the line in bold above. Is it not posssible to check if a condition != true in Javascript?
 
Try this instead:

Code:
var radiochecked = false;
for(j=0;j<ContactForm.plan_id.length;j++)
  {
  el = ContactForm.plan_id[j];
  if(el.checked)
    {
    radiochecked = true;
    break;
    }
  }
if (radiochecked == false)
  {
  alert("Please choose a plan type");
  ContactForm.plan_id[0].focus();
  return false;
  }
return true;

What I've done is use a variable as a flag, setting it first to false. If ANY of the radio buttons is checked, then the variable is set to true, and the code breaks out of the loop. Then the value of the variable is tested. If no radio buttons were checked, then it'll still be false, and your error message will pop up and the function will return false.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top