View Full Version : Help - Validate CheckBox[] Array

08-27-2007, 12:43 AM
How can I validate a checkbox array using javascript? :confused:

I am using HTML and PHP to parse the data.

HTML Code:

<input type="checkbox" name="game[]" id="game" value="game" />


PHP Code:

$state = Trim(stripslashes($_POST['game']));

if(isset($_POST['game']) && is_array($_POST['game']))
foreach($_POST['game'] as $key=>$val)
case 'Game Type':
$email = "myemailaddress";
$Body .= <<<EOF

08-27-2007, 01:08 AM
What is there to validate? I'm not sure what you'd be checking-- if it's on or off? if (document.form1.checkBox.checked) {alert("yeah it's checked alright");}

08-27-2007, 01:52 AM
If you want to check a group of checkboxes. You will have to loop through the input tags to see if the checkboxes are checked or not.

If you are populating the checkboxes with a PHP array, be sure to give the same value to the name as you do for the id.
Having the same value doesn't make much sense either:
<input type="checkbox" name="game[]" id="game[]" value="game[]" />

Here's an example:
<script type="text/javascript">
function chkBox() {
var chkedBoxes = [], i = 0, inputs = document.getElementsByTagName('input');
while (i<inputs.length) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
// it's checked
inputs[i].checked = false;
alert(chkedBoxes.length + ' item(s) were selected\n' + chkedBoxes);

<form id="gameform" name="gameform" method="post" action="" enctype="multipart/form-data">
<input type="checkbox" name="game1" id="game1" value="game1" />
<input type="checkbox" name="game2" id="game2" value="game2" />
<input type="checkbox" name="game3" id="game3" value="game3" />
<input type="checkbox" name="game4" id="game4" value="game4" />
<input type="button" onclick="chkBox()" value="Run Check">

08-27-2007, 02:48 PM
I'm sorry. The values I entered are fictitious :

<input type="checkbox" name="game[]" id="game[]" value="game[]" />

This is a true name - name="game[]"

Thanks for your suggestion, but the script/html doesn’t work correctly with my PHP code.

name="game[]" is an array. PHP will only display the html data (array) if it's checked. How can I incorporate name="game[]" into your script/html?