PDA

View Full Version : Radio button validation



neo_philiac
08-27-2008, 07:37 PM
I got this code from javascriptkit. And I added a few code to validate the radio button and checked boxes. It works for check boxes but not for radio buttons



function checkrequired(which){

var btn = valButton(document.Reg.race);

var pass=true
if (document.images){
for (i=0;i<which.length;i++){
var tempobj=which.elements[i]

if (tempobj.name.substring(0,8)=="required"){

//All the document.Reg.box<number>.checked == false are to check for check boxes

if (((tempobj.type=="text"||tempobj.type=="textarea")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&tempobj.selectedIndex==-1) || (document.Reg.box1.checked == false && document.Reg.box2.checked == false && document.Reg.box3.checked == false && btn == null )){
pass=false
break
}
}
}
}
if (!pass){
alert("One or more of the required elements are not completed. Please complete them, then submit again! Please Make sure you select at least one checkbox")
return false
}
else
return true
}

//To validate radio buttons

function valButton(btn) {
var cnt = -1;
for (var i=btn.length-1; i > -1; i--) {
if (btn[i].checked) {cnt = i; i = -1;}
}
if (cnt > -1) return btn[cnt].value;
else return null;
}



Help please !

Thanks

clueful
08-27-2008, 11:40 PM
I got this code from javascriptkit. And I added a few code to validate the radio button and checked boxes. It works for check boxes but not for radio buttons
Checkboxes and radio buttons are read in the same way. Remember that if there is only one element in a group, then the .length property does not exist.

neo_philiac
08-28-2008, 12:40 PM
Does that mean I am doing it right ?

I have 2 in a group!


<td width="314" height="24"> <span class="body">
<Input type = 'Radio' Name ='race' value= 'Male'>Male
<Input type = 'Radio' Name ='race' value= 'Female'>Female<br>
</span>

Thanks

clueful
08-28-2008, 01:28 PM
Does that mean I am doing it right ?

I have 2 in a group!


<td width="314" height="24"> <span class="body">
<Input type = 'Radio' Name ='race' value= 'Male'>Male
<Input type = 'Radio' Name ='race' value= 'Female'>Female<br>
</span>

ThanksHave you alerted the value returned by the function? If it's as expected, you'll know to look elsewhere.