Include also unchecked boxes in the POST variable – multiple checkbox

I am using the code below in my php file to get the values from a multiple checkbox.

    if(!empty($_POST['check_list'])) {
        foreach($_POST['check_list'] as $check) {
                update_comment_meta($check, 'consider', 1);
        }


    }

The problem is that this code is apparently putting in the array $_POST['check_list'] only the checked values.

Read More

My need is to perfom the function update_comment_meta also on uncheked values, by putting ‘0’ as the third parameter instead of ‘1’.

For more details, I give the code generating the HTML form:

<form action="" id="primaryPostForm" method="POST">

<?php    
         $defaults = array(
    'post_id' => $current_post); 
         $com= get_comments( $defaults );

        foreach ($com as $co) {
    if(get_comment_meta($co->comment_ID, 'consider', true)==1) {
    ?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" checked="checked">

    <?php }
    else {
    ?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" >
    <?php
    }}
</form>

Your usual help is always appreciated.

Related posts

Leave a Reply

2 comments

  1. sending unchecked value to post is somewhat not that easy.Better solution is that you name checkbox in a way using which you can easily iterate over them in post page.

    Use hidden input along with checkbox.Checkbox prioritize over hidden input.

    <form>
      <input type='hidden' value='0' name='check_box_con'>
      <input type='checkbox' value='1' name='check_box_con'>
    </form>
    

    Now after submit, as both have same name , check_box_con will show hidden field value if unchecked , else will override and show original.

    For more see
    Post the checkboxes that are unchecked

  2. Here is the solution I used ( based on PeeHaa comment):

            if(!empty($_POST['check_list'])) {
            foreach ($com as $co) {
    
            if (in_array($co->comment_ID,$_POST['check_list']))
            update_comment_meta($co->comment_ID, 'consider', 1);
    
            else 
             update_comment_meta($co->comment_ID, 'consider', 0);
            }
            }
    

    In fact POST variable works like this with checkboxes, so the simple way is to use server side language to know what are values not sent via POST.

    Thank you for your time.