Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

Checking if a radio button is selected in a group - code


<head>

<script language="javascript">

function checkRadio(){

/*
Define local variables
*/
var radioReference var aRadioButtonIsSelected /*
The loop will set aRadioButtonIsSelected to true if a radio
button is checked, so it's initialized with false.
This allows the statement if(aRadioButtonIsSelected) to
be evaluated with the real answer.
*/
aRadioButtonIsSelected = false /*
Get the reference to group1 in myForm
*/
radioReference = document.myForm.group1 /*
Iterate up to the last radio button but cancel the loop if one is checked
*/
for(var i=0; i<=radioReference.length-1; i++){
if(radioReference[i].checked) { //Is the radio button checked?
aRadioButtonIsSelected = true //Set aRadioButtonIsSelected to true
break //Cancel the loop
}
}
if(aRadioButtonIsSelected){ //Is aRadioButtonIsSelected true ?
alert("Going to send the form") //Show the message in an alert
}else{ //No radio button is selected
alert("You did not choose an option") //Show the message in an alert
}
}
</script>
</head>

<!--

Define the form elements in the body of the document
--> <body><!-- Open the body tag -->
<form name="myForm"><!-- Open the form element and give myForm as it's name -->
<!--
Define button
and make it call checkRadio when clicked
-->
<input type="button" value="Send" onclick="checkRadio()"> <!--
Define the radio buttons
and insert both radio buttons into group1
-->
<input type="radio" name="group1">Yes
<input type="radio" name="group1">No
</form><!-- Close the form -->
</body><!-- Close the body element -->


Close