Click to See Complete Forum and Search --> : Validation of radio buttons


thegooner
10-18-2005, 04:38 AM
Hi

I need to validate whether or not a radio button has been selected using javascript.
I have been using this:

function valbutton(thisform) {
myOption = -1;
for (i=0; i<thisform.radiobutton.length; i++) {
if (thisform.radiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("Please Select one of the Radio Buttons");
return false;
}
thisform.submit(); // this line submits the form after validation
}

This works fine, but I need something that will be able to do the same with radio buttons that are named as an array. Example, my set of radio buttons that I want to validate are all called " radiobutton[2]".

I tried changing the above script to use this new name, but it no longer works.

Anyone know how I can do this?

Thanks

Fang
10-18-2005, 06:18 AM
for (var i=0; i<thisform.elements['radiobutton[2]'].length; i++) {
if (thisform.elements['radiobutton[2]'][i].checked) {
alert(i);
}
}

thegooner
10-18-2005, 06:33 AM
for (var i=0; i<thisform.elements['radiobutton[2]'].length; i++) {
if (thisform.elements['radiobutton[2]'][i].checked) {
alert(i);
}
}


EXCELLENT!

Thanks for your time..... REALLY appreciated!

One last thing...

I want to loop a function through all my sets of radio buttons, so how would I loop through a form that contained 2 or more sets of radio buttons, named radiobutton[1] and radiobutton[2] etc. I would like to loop it as if I didn't know how many sets of radio buttons there were, using a "for" loop if possible.

How would that work with your code above.

Many thanks for this!!

Fang
10-18-2005, 06:51 AM
For radiobutton[1] and radiobutton[2] :
function val(thisform) {
for (var r=1; r<3; r++) {
for (var i=0; i<thisform.elements['radiobutton['+r+']'].length; i++) {
if (thisform.elements['radiobutton['+r+']'][i].checked) {
alert('radiobutton['+r+'] : index'+i);
}
}
}
}

thegooner
10-18-2005, 06:59 AM
For radiobutton[1] and radiobutton[2] :
function val(thisform) {
for (var r=1; r<3; r++) {
for (var i=0; i<thisform.elements['radiobutton['+r+']'].length; i++) {
if (thisform.elements['radiobutton['+r+']'][i].checked) {
alert('radiobutton['+r+'] : index'+i);
}
}
}
}



I can't thank you enough FANG.

That's solved my problem.

If I'm ever in Holland I'll be sure to get you a beer!

Cheers