Like it or lump it

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

50 Comments

  1. Justin

    Very helpful. Thanks!

  2. Why not use foreach($optionArray as $option) instead of for($i=0; $<count(…..) !?

  3. admin

    Using a foreach is a great way to do it, but is a little harder for php beginners to understand. Thanks.

  4. Why not just use implode()?

    echo implode(”, $_POST[‘chk_group’]);

  5. should’ve read :

    echo implode(”, $_POST[‘chk_group’]);

    html got filtered out!

  6. Thank you, just what I was looking for…

  7. adam

    Seriously, thank you for this. Had the same issue with only the last item coming over and was about to pull out my hair.

  8. Sachin Viduranga

    Hey Man , You Saved My Time! , Thx Bro

  9. Derya S.

    Thank you very much 🙂 Mujjxxx

  10. kitty

    muy buena solucion pero no puedo enviar como matriz trabajo con jquery easyui y MVC

  11. Jonny

    my best suggestion to you, is stop using admin as your comment name. Who is Admin, is it Mark, John, or how about Ravi?

  12. Andy

    Only an uber troll would take time out of their day to give me a hard time about my username on this blog. Well played, my friend. I changed it for you.

  13. Paul

    I Love Your Bunny!

  14. Nice! It works perfectly.
    Thanks a lot.

  15. ant

    sweet find, andy.
    my form processing scripts are a lot cleaner thanks to this 😀

  16. David

    Hi,

    Great little bit of kit, how would i put the result in this?
    $message is sent through email

    $optionArray = $_POST[‘chk_group’];
    for ($i=0; $i<count($optionArray); $i++) {
    echo $optionArray[$i];
    }

    $message = "\n\n Name: $name \n\n Email: $email_address \n\n About Me: \n\n $message \n\n \n\n Here is $name's CV: $file_name";

  17. Andres Padilla

    Muchas gracias por tu ayuda

  18. Ruben

    Muuuchas Gracias.
    Thanks!

  19. This saved me so much time!

  20. Feilian

    Oh my god, thank you heaps!
    Had been trying to get my checkbox to work for a few days.
    Thank you so much for posting these solutions!!!!!1

  21. Govardhan

    great job!!

  22. abhishek

    how to retreive values in javascript?
    ty

  23. Thanks! W3C documentation fails on listing this. You saved me a lot of trouble. 🙂

  24. Thanks……. Nice! It works perfectly.
    Thanks a lot.

  25. Dhaval

    Good.. it makes so easy to retrieve group values

  26. Nice and very easy to understand example, most ppl forgot to explain how to retrieve the values in PHP. Thank you!

  27. Very useful. I just wonder … now that they all have identical names, how to address all these checkboxes in JavaScript if I want to toggle them on/off all at once?

  28. Very helpful!
    You saved me much time!
    Thanks

  29. Roberto

    thanks

  30. Varun

    This dint worked as it was supposed to…
    the problem is:

    1)Wen i give the name as explained in this example it gets difficult to retrieve it with php..It only counts one array not three as it should in the context of this example..

    2)wen you use array in such way which help in data retrieving:-
    Value 1

    Value 2

    Value 3

    in this it solves the purpose of data retrieving but it at the same time allows multiple options to get checked….!!!
    Do you have any solution for this???

  31. Varun

    2)wen you use array in such way which help in data retrieving:-
    name=”chk_group[0]”
    name=”chk_group[1]”
    name=”chk_group[2]”

    in this it solves the purpose of data retrieving but it at the same time allows multiple options to get checked….!!!
    Do you have any solution for this???

  32. JeroenMe

    @Anonymous

    You could just give them the same class and loop them using javascript and toggle them one by one.

  33. OMen

    Thank you.. very useful!

  34. Mike

    @abhishek
    var jsvar =

    Also, I googled this thinking there might need to be a special way to do this, and it turns out there isn’t anything special to do, just like you premise at the beginning of this article. However, for me there was no issue as you describe with getting the values from checkboxes with the same names. Here’s the code I got from elsewhere to put the url flags into an array:

    $query = explode(‘&’, $_SERVER[‘QUERY_STRING’]);
    $params = array();
    foreach( $query as $param )
    {
    list($name, $value) = explode(‘=’, $param);
    $params[urldecode($name)][] = urldecode($value);
    }

  35. Artur

    Super and very easy to use.

  36. Rolando

    Very helpful, thanks

  37. Allison

    Yes! I was looking at examples and, you’re right, they’re all wrong: checking multiple boxes with the same name just overwrites them in the post parameters. Thought I was losing my mind. Thank you for writing this!

  38. Peter

    Just wanted to drop in a quick “thanks” from a novice PHP programmer. I’ve been banging my head against the wall for quite some time on this and FINALLY found the info I needed here. Short, simple and to the point. Thanks again!

  39. Adrian

    Thanks – you just saved my day. Can’t believe I didnt notice the missing [] in the name attribute !

  40. Just the code i need. explode() function also worked perfectly. Thanks men.

  41. Googled “html form group checkbox” and I am not disappointed! Thanks man

  42. @Justin
    Thanks, that helped!!

  43. Glenn N

    Since the OP did not specify the server-side, allow me to offer the simple Python solution. No explosions or implosions are required!

    import cgi # package for processing forms and such cgi things
    form = cgi.FieldStorage() # all the form args
    checks = form.getlist(‘chk_group[]’)

    If nothing is checked, then checks=[], an empty list; otherwise it is a list of the values of the checked boxes. I think this is much more satisfying than PHP.

  44. Sankis Dudd

    Sankis DUDE!!

  45. iqbal

    I want to show checkbox when i click option group/dropdown . Could you give me solution with this?

  46. Thanks I was doing the name thing without the []’s and for the life of me couldn’t figure out what was going wrong – thanks for awesome tip!!

  47. Troy

    Andy,
    I think it might be worth mentioning that a web site that I built in approximately 1997 used multiple same-name checkbox inputs with the name=”chk_group” method …without the [ ]

    Back then it actually did work for year, the browser’s POST would simply send multiple same-named values.

    At some point it stopped working, I’m not sure when, because nobody told me that it had stopped working, they just suffered-with. Finally I discovered it. I presume browsers changed the way GET and POST of same-named inputs were handled at some point. Interesting the W3C hasn’t changed this in their online basics manual!!!

    I take it back, I just checked the activity log, and the last multiple same-name checkbox POST occurred on 5/5/2012, and never any more after that.

  48. jack

    thank you!

  49. Fabio

    Thanks, you’re right!
    Many examples are wrong.

  50. For anyone else who wanders in from Google, the W3C docs don’t mention adding [] because it’s PHP-specific.

    Other languages generally handle it by having an alternative getter which returns a list rather than just one entry. (eg. When I’m programming in Django, I’d use request.POST.getlist(‘chk_group’) for this)

Powered by WordPress & Theme by Anders Norén