Sei sulla pagina 1di 2

/*javascript code (generalised) for any no.

of "checkbox" validation*/

/*must be written inside "function validate()"*/

var j=0; /*from here onwards we have written


code for checkbox validation(generalised-taking name attribute)*/
var s=""; /*taken a variable 'j' and
initialized it to zero,similarly taken a var 's' and initialized it to 'blank'*/
var checkarray=new Array(); /*taken an array 'checkarray'
of unknown size*/
var check=document.getElementsByTagName("input"); /*taken all the input fields
and stored it to a var 'check',remember 'check' will contaibn an array of input
fields*/

for( var i=0; i< check.length; i++) /*traversing the array of input
fields*/
{
if(check[i].type=="checkbox") /*checking the 'type' attribute
of each input field*/
{
if(s!=check[i].name) /*as we have initialized 's' by
'blank',so this condition will be true for the 1st checkbox of 'name'=lang' and
similarly when other names appear*/
{

checkarray[j]=check[i].name; /*putting the each


different'name'*/
j++; /*incrementing j for next name
to be placed in the array*/
s=check[i].name; /*putting the 'name' in 's' */
}
}
}

for( var k=0;k<checkarray.length;k++) /*now we will


traverse the 'checkarray' array upto its length and call a function
'checkBoxValidation'*/
{
if(!checkBoxValidation(checkarray[k])) /*we will
pass each 'name' and if the return value of the function is false then */
{
alert(document.getElementsByName(checkarray[k])
[0].alt); /*alert will be shown using 'alt' tag,[0]is used to fetch the 1st alt of
1st 'name' */
return false ; /*return the control to console*/
}
}
/*the "function checkBoxValidation()" code should be witten outside function
validate()*/
/*the code is written below*/

function checkBoxValidation(name) /*as we have passed checkarray[k] with the func


call,each checkarray[k] will be accepted in 'name' parameter written here*/
{

var chk= document.getElementsByName(name); /*it will return how many


checkboxes are there of that 'name' as an array*/
for( var m=0;m<chk.length;m++) /*traversing the 'chk' array
,that is for 'lang' the chk.length will return 3 and for 'soft' the length will be
3 again */
{
if(chk[m].checked==true) /*checking whether any chckbx
of name='lang' and also of name='soft' is selected or not*/
{
return true; /*if true the return true to
the function call*/
}
}
return false; /*else return false to the
func call*/
}

Potrebbero piacerti anche