Click to See Complete Forum and Search --> : Radio button validation


noeldebono
09-20-2004, 03:05 AM
I have this javascript code that should check that a radio button is pressed before commiting. It is working fine acept for the fact that if I have only one radiobutton to choose from it is telling me to choose an option even if the only radio button on the screen is pressed! Can someone help me and tell me what is the problem with this code?

CODE:

<script>
function checkRadios() {
var el = document.forms[0].elements;
for(var i = 0 ; i < el.length ; ++i) {
if(el[i].type == "radio") {
var radiogroup = el[el[i].name]; // get the whole set of radio buttons.
var itemchecked = false;
for(var j = 0 ; j < radiogroup.length ; ++j) {
if(radiogroup[j].checked) {
itemchecked = true;
break;
}
}
if(!itemchecked) {
alert("Please choose an option.");
if(el[i].focus)
el[i].focus();
return false;
}
}
}
return true;
}
</script>CODE

javaNoobie
09-20-2004, 04:52 AM
if I have only one radiobutton to choose fromSince you only have one to select from and it is compulsory, make it selected by default. Then there will be no need for validation.

*edit: changing codes to the following seems to solve the problem var radiogroup = document.getElementsByName(el[i].name);