We'll give you something to cry about

HTML Multi checkbox set – the correct way to group checkboxes

I was setting up an HTML form today and I wanted to group some options together in a multi checkbox set, allowing a user to select multiple options in a category. I usually just give each checkbox a unique name and parse all of the individual values in PHP, but this has always struck me as an ugly way to handle this use case.

As I was looking up the syntax for an HTML checkbox, I found a lot of info that said I could simply name all of the checkboxes the same and it would group all of the values together like this:

<input type="checkbox" name="chk_group" value="value1" />Value 1<br />
<input type="checkbox" name="chk_group" value="value2" />Value 2<br />
<input type="checkbox" name="chk_group" value="value3" />Value 3<br />

But this doesn’t work. When you POST the values to PHP, you only receive the last item selected in the group. The annoying thing is that a lot of the examples online show this same syntax even though it’s clearly wrong. After digging a little deeper, I found this forum post with the correct syntax. Adding square braces to the checkbox name creates an array of the selected values in the group:

<input type="checkbox" name="chk_group[]" value="value1" />Value 1<br />
<input type="checkbox" name="chk_group[]" value="value2" />Value 2<br />
<input type="checkbox" name="chk_group[]" value="value3" />Value 3<br />

This can be retrieved in PHP with a simple loop:

<?php
if (isset($_POST['chk_group'])) {
    $optionArray = $_POST['chk_group'];
    for ($i=0; $i<count($optionArray); $i++) {
        echo $optionArray[$i]."<br />";
    }
}
?>

Simple! I thought I should post this correct solution in the hopes that it might help someone else wade through all of the wrong information out there.

Previous

Fast Game Prototyping with Flashpunk and Minimal Comps

Next

Augmented Reality Air Hockey – A Game Experiment

6 Comments

  1. linquant

    Thanks

  2. Lev

    5 Years later, still very relevant. Thanks so much! 🙂

  3. Donald

    thanks! very useful.
    googled “html input checkbox multiple” and this article came up first

  4. Claire

    Seriously, thanks so much! Saved me a bunch of time.

  5. needed in java script any how thanks

  6. Thank you for the information. Unfortunately it didn’t work for me as shown. This is my version that does exactly what I need:

    	if(isset($_POST['selection'])) {
    		foreach($_POST['selection'] as $option) {
    			echo "".$option."";
    		}
    	}	
    

    I’ll be feeding the option choices into a sql string, but that’s outside of the subject at hand.

Powered by WordPress & Theme by Anders Norén