Get POST data from multiple checkboxes?

Currently it's just catching your last hidden input. Why do you have that hidden input there at all? If you want to gather information if the "Other" box is checked, then you have to hide the

<input type="text" name="other" style="display:none;"/> 

and you can show it with javascript when the "Other" box is checked. Something like that.

Just make the name attribute service[]

<li>
<label>What service are you enquiring about?</label>
<input type="checkbox" value="Static guarding" name="service[]">Static guarding<br />
<input type="checkbox" value="Mobile Patrols" name="service[]">Mobile Patrols<br />
<input type="checkbox" value="Alarm response escorting" name="service[]">Alarm response escorting<br />
<input type="checkbox" value="Alarm response/ Keyholding" name="service[]">Alarm response/ Keyholding<br />
<input type="checkbox" value="Other" name="service[]">Other</span>
</li>

Then in your PHP you can access it like so

$service = $_POST['service'];
echo $service[0]; // Output will be the value of the first selected checkbox
echo $service[1]; // Output will be the value of the second selected checkbox
print_r($service); //Output will be an array of values of the selected checkboxes

etc...


Name the fields like service[] instead of service, then you'll be able to access it as array. After that, you can apply regular functions to arrays:

  • Check if a certain value was selected:

     if (in_array("Other", $_POST['service'])) { /* Other was selected */}
    
  • Get a single newline-separated string with all selected options:

     echo implode("\n", $_POST['service']);
    
  • Loop through all selected checkboxes:

     foreach ($_POST['service'] as $service) {
         echo "You selected: $service <br>";
     }
    

Tags:

Php

Post