Checkbox Form Validation

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Checkbox Form Validation

Post by spacebiscuit »

Hi guys,

I am trying to write some form validation code to check that at least one checkbox is checked when an HTML form is submitted.

The problem is that the number of check boxes is dynamically generated and so I do not know how many checkboxes there are. The variable name of each checkbox is dynamically created as follows:

rec_con_assign_1, rec_con_assign_2, rec_con_assign_3... and so on.

This is what I have written:

Code: Select all

var flag=0;
var counter=1;

while (rec_con_assign_[counter]){

if(form.rec_con_assign_[counter].checked){
     flag++;
                                                               }
     counter++;

                                               }

if (flag == 0){
     alert ("You must check one and only one checkbox!");
     return false;
              } 
It does not work though, I suspect because I write in PHP and so I am sure there is just an error in my code?

Thanks in advance,

Rob.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Checkbox Form Validation

Post by social_experiment »

The code below is something i used in a site i created, i had an amount of radio buttons that had to be selected before the form could be submitted. Maybe you could modify it to work for your requirements. Hth

Code: Select all

var allInputs = document.getElementsByTagName('input').length;

for (i = 0; i <= allInputs; i++)
{
element = document.offerForm;
if (element.type == 'radio')
{ 
//
 if (element.checked == true)
 {
    j = j + 1;				
 }
//			
}
}
			
 if (j != 6)
 {
 alert('All radio buttons has to be checked' + 
' before the form can be submitted.');
 return false;
 }
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: Checkbox Form Validation

Post by IGGt »

Am I reading this right:
it looks at ALL the <input> tags (radio buttons, check boxes etc.)
then IF it is a RADIO button, it looks to see if it is CHECKED, in which case it increments j by one
Then finally looks to see if 'j' is not 6.

I have tried something very similar, but it doesn't work:

Code: Select all

function ValidateDBSelect(){
	
var allInputs = document.getElementsByTagName('input').length;
for (x = 0; x <= allInputs; x++)
	{
		element = document.DBReturn //the name of the form it applies to
		if (element.type == 'radio') 
		{
			if (element.checked == true)
			{
				a = a + 1;                      
			}           
		}		
	}
                       
if (a != 3)
{
		alert('Please Select a Database.');
		return false;
}
The page has 3 groups of radio buttons, and so there should always be 3 selected, but even if I uncheck some, or tell it to look for "a !=5" the javascript doesn't seem to do anything.
I know the form is calling it, because if I put "a = 0" at the top, and then "a == 0" at then end I get the alert. For some reason the bit in the middle that checks the buttons, doesn't seem to work.
Any ideas on this would be highly appreciated.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Checkbox Form Validation

Post by social_experiment »

EDIT: Here is a complete working example. There previous snippet of code was taking from a function and therefore incomplete. The one below i used in the following manner

Code: Select all

<form action="" method="post" id="offerForm" onsubmit="return ValidateDBSelect();" >
Each time a radio element is encountered a check is done to see if it is checked, if not, j is increased by 1. The value of j is then compared against the amount of radio input fields and if it is equal to that amount, no radio buttons have been checked. From this you can determine if any radio buttons have been selected or how many.

Code: Select all

function ValidateDBSelect(){
	
	var allInputs = document.getElementsByTagName('input').length;
	var j = 0;
	
	for (i = 0; i <= allInputs; i ++)
	{
		element = document.getElementById('offerForm');
		if (element.type == 'radio')
		{
			if (element.checked == true)
			{
				j = j + 1;
			}
		}
		if (j != 2)
		{
			alert('Select something');
			return false;
		}
	}
	
	return true;
	
}
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: Checkbox Form Validation

Post by IGGt »

After some fiddling / tweaking I have got the below script, which allows me to check for type (radio / checkbox) and name of each element. From here I can check each 'group' of elements to ensure at least one has been selected from each group.

Code: Select all

function ValidateDBSelect(){
    var TLength = document.DBReturn.elements.length;

    a = 0;
    b = 0;
        
    for (x=0; x<TLength; x++)
    {
        var type = DBReturn.elements[x].type;
	    var name = DBReturn.elements[x].name;
        //radio button
        if (type=="radio" && name=="group1" && DBReturn.elements[x].checked){
        	//alert("Radio Button in position " + x + " has a name of " + name + ", and is checked.");
            a = a + 1;
        }
        // Check Box
         if (type=="checkbox" && name=="cb1" && DBReturn.elements[x].checked){
        	//alert("Checkbox in position " + x + " has a name of " + name + ", and is checked.");
            b = b + 1;
        }
	}
        
	if (a != 1){
    	alert("Please Select a radio Button from Group1");
    	return false;
	}
	if (b == 0){
    	alert("Please Select at Least One Checkbox");
    	return false;
	}
};
cheers for all your help.
Post Reply