What do you like best?
mommy
toys
monkeys
Validating Radio Button Groups
By setting the value of the variable, "found_it" equal to the checked button's value, the original button loop script can easily find which button was checked. But what happens if no buttons are checked? We need a way to handle this situation, especially if you want to require a button from a group be checked.

Before getting into the additional validation scripting, I want you to notice something about the found_it variable in the original script - it is declared but not initialized. Or in plain English, it is not assigned a value. Because it was not assigned a value initially, it has an original value of null, and will stay that way unless its value is reset to a checked button's value.
var found_it //initial value is null because we gave it no other value

for (var i=0; i<document.form.group1.length; i++)  {
if (document.form.group1[i].checked)  {

found_it = document.form.group1[i].value //set found_it equal to checked button's value

}
}
To check for the possibility of the user leaving the entire group unchecked, an additional if statement only needs to test the variable "found_it" for a value of null. The if/else can be constructed in two different ways using two different operators. The first example uses the "not equal to" (!=) comparison operator. Remember - comparison operators compare two operands for equality.
if(found_it != null){ //if found_it is NOT equal to null, a button HAS been checked

alert(found_it)

}

else{

alert("Please check a radio button")

}
The second if/else construct uses the "not" (!) logical operator. Logical operators test two boolean values for equality. The not operator evaluates a null value in the same way it evaluates a false value, so it can be used to test found_it to see if it has been assigned a value. To keep from becoming confused by the not operator, just think of it as a shorthand way of saying, "found_it==false".
if(!found_it){ //if found_it is equal to false or null, a button has NOT been checked

alert("Please check a radio button")

}

else{

alert(found_it)

}
In this example, we alert the user to please check a radio button. If our form was actually wired to a CGI script on the server, or set to some other action, we could also return false to the onsubmit handler to keep the form from submitting as demonstrated in the Stop That Form example.

Although I've used radio buttons in the last few examples, the same concepts can be applied to checkbox groups as well.

View the Source