views:

398

answers:

2

Hi,

I have a checkbox group in my html form.The check box group contains array. My question is how validate the checkbox array using jquery and get the array value in php

The code given below

<input type="checkbox" name="go[]"  value="1" /><label>Married</label><br>
<input type="checkbox" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" name="go[]" value="4"/><label>Minor</label>

Thanks in advance.

+1  A: 

If you mean how to validate check boxes because they contain [], here is one solution using ids instead:

<script type="text/javascript">
function validate()
{
 var proceed = true;

 for(var i = 1; i <= 4; i++)
 {
  if (!$("#" + i).is(':checked'))
  {
   proceed = false;
   break;
  }
 }

 if (proceed == true)
 {
  return true;
 }
 else
 {
  alert('All Fields Are Required !!');
  return false;
 }
}
</script>

And the html form might look like this:

<form action="frm" method="post" onsubmit="return validate();">

 <input type="checkbox" id="1" name="go[]"  value="1" /><label>Married</label><br>
 <input type="checkbox" id="2" name="go[]" value="2" /><label>Widowed</label><br>
 <input type="checkbox" id="3" name="go[]" value="3" /><label>Single</label><br>
 <input type="checkbox" id="4" name="go[]" value="4"/><label>Minor</label>

 <br />
 <input type="submit">
</form>

For PHP:

// get checkboxes array
$chk_array = $_POST['go'];

Now you can manipulate $chk_array array in any way you want:

Note:

$chk_array[0] // contains your 1st checkbox value
$chk_array[1] // contains your 2nd checkbox value
$chk_array[2] // contains your 3rd checkbox value
$chk_array[3] // contains your 4th checkbox value

In php, arrays start from 0 index.

Thanks

Sarfraz
A: 

I think you're trying to use the jQuery Validation plugin to make sure that at least one checkbox from your group is checked.

The Validation plugin doesn't like input names with brackets in them. Try this in your form's validate method:

rules: {
  'go[]': {  //since it has brackets, the name must be in quotes to work
     required: true,
     minlength: 1
   }
croceldon