Programmed Under The Influence

Commenting… you’re doing it right :D

These are two examples of my new commenting system:

  • What!? No Way! (in alpha)
  • Pollacio.us (coming shortly)
Posting checkbox values with PHP and jQuery

For some time I had trouble figuring out how to post checkbox results using jQuery’s $.post function after submitting a form. I searched many different sites finding pieces of the a solution that would fit my needs.
Anyway here’s what I got:

1) Let’s create a simple form.

    <form id="my_form" onsubmit="return processForm()">
        1) <input type="checkbox" class="option" name="options[]" value="1" /><br />
        2) <input type="checkbox" class="option" name="options[]" value="2" /><br />
        3) <input type="checkbox" class="option" name="options[]" value="3" /><br />
        <input type="submit" value="Submit" />
    </form>

2) Create the javascript to handle the form submission.

    function processForm() {
        var options = $('#my_form :input.option');
        var option_array = new Array();
        
        $.each(options, function(index, element) {
            if ($(element).is(':checked')) {
                option_array.push($(element).val());
            }
    
        // Post options to action file
        $.post('/your/path/to/action/file.php', {'options[]': option_array});
        
        return false;
    }

3) Handle the form submission using PHP.

    <?php
        foreach ($_POST['options'] as $option) {
            /* Do whatever you want with your options here. */
        }
        
        // Or you can just print the results to the screen for test purposes
        print_r($_POST);
        exit;
    ?>