...

View Full Version : Radio Validation not working



jcdevelopment
09-06-2011, 09:55 PM
I wrote a function to to validate some elements in my form and for some reason I can't seem to figure out why my radio validation is not working. There are about 3 to 4 radio buttons. all with the same name, but i need to make sure that at least one out of this group is selected.

Below is my code. Any help would be very useful. Thanks!

JS:


<script type="text/javascript">

function validate_required(field,alerttxt,select)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}

}

function validate_form(thisform)
{
with (thisform)
{
if (document.getElementsByName('sleeper').checked==false)
{
window.alert('Please select a sleeper')
return false;}
}
} //last
</script>


Form:


<form name="week_picks" method="post" action="confirm.php" onsubmit="return validate_form(this)">


<input name="sleeper" type="radio" value="<?=$sleeper;?>" />

<input name="sleeper" type="radio" value="<?=$sleeper;?>" />

<input name="sleeper" type="radio" value="<?=$sleeper;?>" />

etc...
</form>

DaveyErwin
09-06-2011, 10:22 PM
you need to first get the collection
(many examples in this forum)
then loop through and check
each element

Old Pedant
09-06-2011, 11:15 PM
And why would you use document.getElementsByName('sleeper') instead of simply

function validate_form(thisform)
{
if ( getRadioValue(thisform.sleeper) == null )
{
alert('Please select a sleeper')
return false;
}
... other validation ...
}

function getRadioValue(rbgroup)
{
if ( rbgroup.length == null ) return rbgroup.checked ? rbgroup.value : null;
for ( var r = 0; r < rbgroup.length; ++r )
{
if ( rbgroup[r].checked ) return rbgroup[r].value;
}
return null;
}
...


N.B.: That first line in the getRadioValue function is only needed just in case you might happen to have some radio button "group" that only has one radio button in it. If that happens, you won't really have a group (that is, a collection), so you have to check the single button element.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum