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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Radio button validator works for list, but not for just one?

Status
Not open for further replies.

charanch

Programmer
Jan 3, 2004
55
US
Hi there, I have the following script to validate a form radio button. The visitor is registering for a class and they must choose a class before moving on. This script works great with a list of items but if there is only one item and even when it's selected, the alert box comes up anyway. The list pulls from a SQL database. Any ideas on how to fix this or a better way to handle it would be greatly appreciated. Thanks in advance!
Code:
<script language="JavaScript">
function validateForm() {
with (document.frmStates) {
var alertMsg = "You must choose a course to register.";
radioOption = -1;
for (counter=0; counter<register.length; counter++) {
if (register[counter].checked) radioOption = counter;
}
if (radioOption == -1) alertMsg += "\nregister";
if (alertMsg != "You must choose a course to register.") {
alert(alertMsg);
return false;
} else {
return true;
} } }
</script>
 
.length is only defined for arrays. if there is only one radio button, it is not an array and therefore cannot be looped through.

try this simple example, it should get you going in the right direction:

Code:
<form name="f">
<input type="radio" name="r1" />
<input type="radio" name="r1" />
</form>

<script type="text/javascript"><!--

if( document.f.r1.length ) {
    for ( var i = 0; i < document.f.r1.length; i++ ) {
        alert(i);
    }
} else {
    alert('only 1');
}

//--></script>



*cLFlaVA
----------------------------
[tt]mr. pibb + red vines = crazy delicious![/tt]

[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top