Wordpress Themes - Reference And Education Articles - Online Advertising - Debt Consolidation - Reduce Debt

PDA

View Full Version : Looping through a set of checkboxes to authenticate


Sean@WMS
Oct 30th 2008, 6:02 pm
I have a form I'm working on with a series of checkboxes, reg0 through reg11, that I'm trying to validate to make sure at least one was checked. However, there are other checkboxes on the form, so I can't just simply count up all of the checkboxes -- I need to check against this specific set of them.

Here's what I've tried:

// Check to make sure at least one workshop was selected
var checkbox_choices = 0;
for (counter = 0; counter < 11; counter++)
{
if (form.reg[counter].checked)
{ checkbox_choices = checkbox_choices + 1; }
}

if (checkbox_choices < 1 )
{
alert("Please select at least one workshop." + checkbox_choices);
form.reg0.focus();
return (false);
}


I also tried if (form.reg+counter.checked), and that had the curious effect of not erroring, but not counting checkbox_choices either, so it always throws the alert and returns false.

rohan_shenoy
Oct 31st 2008, 2:34 am
<form action="" method="">
<fieldset id="set_of_checkboxes">
<input type="checkbox" ... />
<input type="checkbox" ... />
<input type="checkbox" ... />
</fieldset>

</form>


var set_of_checkboxes=document.getElementById('set_of_checkboxes');
var array_of_all_checkboxes=set_of_checkboxes.getElementsByTagName('input');
//or you may also use
var array_of_all_checkboxes=set_of_checkboxes.childNodes;
//now iterate the array using for...in loop

ranabra
Oct 31st 2008, 8:52 am
Here's another option:

<SCRIPT LANGUAGE="JavaScript">
var checkbox_selected="";

function CheckIfcheckboxButtons()
{
if (checkbox_selected=="")
alert("\nYou must check one of the checkbox buttons.");
else
{
alert("Form has been filled out correctly.");
}
}
</SCRIPT>

<INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">YES
<INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">NO
<INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">MAYBE

<INPUT TYPE="button" VALUE="Check Form Fields" onClick="CheckIfcheckboxButtons()">

Sean@WMS
Oct 31st 2008, 2:02 pm
Thanks, Rohan. Worked like a charm :)


<form action="" method="">
<fieldset id="set_of_checkboxes">
<input type="checkbox" ... />
<input type="checkbox" ... />
<input type="checkbox" ... />
</fieldset>

</form>


JAVASCRIPT Code:
</p>
<p>var set_of_checkboxes=document.getElementById('set_of_checkboxes');</p>
<p>var array_of_all_checkboxes=set_of_checkboxes.getElementsByTagName('input');</p>
<p>//or you may also use</p>
<p>var array_of_all_checkboxes=set_of_checkboxes.childNodes;</p>
<p>//now iterate the array using for...in loop</p>
<p>