How to pass an array of checked/unchecked checkbox values to PHP email generator?

I have added a checkbox to a form that the user can dynamically add rows to. You can see the form here.

I use an array to pass the values for each row to a PHP email generator, and all works fine for other inputs, but I can't get the checkbox to work. The checkbox input currently looks like this:

<input type="checkbox" name="mailing[]" value="Yes">

Then in the PHP I have this:

$mailing = trim(stripslashes($_POST['mailing'][$i]));

But it is not working as expected, i.e. I am only seeing 'Yes' for the first checkbox checked, and nothing for subsequent checkboxes that are checked.

One further issue is that I would like the value 'No' to be generated for unchecked checkboxes.

Could someone help with this?

Thanks,

Nick

Form:

<form method="post" action="bookingenginetest.php">
            <p>
                <input type="checkbox" name="mailing[]" value="Yes">
                <label>Full Name:</label> <input type="text" name="name[]">
                <label>Email:</label> <input type="text" name="email[]">
                <label>Telephone:</label> <input type="text" name="telephone[]">
                <span class="remove">Remove</span>
            </p>
            <p>
                <span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
            </p>

        </form>

Cloning script:

$(document).ready(function() {

                $(".add").click(function() {
                    var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
                    x.find('input').each(function() { this.value = ''; });
                    return false;
                });

                $(".remove").click(function() {
                    $(this).parent().remove();
                });

            });

Answers


$mailing = array();
foreach($_POST as $v){
    $mailing[] = trim(stripslashes($v));
}

To handle unchecked boxes it would be better to set each checkbox with a unique value:

<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">

or

<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">

Then have a list of the checkboxes:

$boxes = array(1,2,3);
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
foreach($boxes as $v){
    if(array_key_exists($v,$p)){
        $mailing[$v] = trim(stripslashes($p[$v]));
    }else{
        $mailing[$v] = 'No';
    }
}

print_r($mailing);

You could also use this with a number of checkboxes instead:

$boxes = 3;
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
for($v = 0; $v < $boxes; $v++){
    if(array_key_exists($v,$p)){
        $mailing[$v] = trim(stripslashes($p[$v]));
    }else{
        $mailing[$v] = 'No';
    }
}

print_r($mailing);

Change the value for each checkbox to something unique:

<input type="checkbox" name="mailing[]" value="Yes-1"> 
<input type="checkbox" name="mailing[]" value="Yes-2"> 

etc. In order to do this from your jQuery code, add another line that assigns the value to the new checkbox:

x.find('input:checkbox').each(function() { this.value='Yes-'+n; }); 

You'll have to define n on the initial page load. Assuming you start with only one "person", just add right above your $(".add").click handler:

var n=1;

And then:

  • in your $(".add").click handler, increment the value of n
  • in your $(".remove").click handler, decrement the value of n

To get checked and unchecked both values in POST place a hidden field with exactly the same name but with opposite value as compared to the original chkbox value such that in this case the value will be '0'

<input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox"  name="chk_name[]"  value="1"/>
 <input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox"  name="chk_name[]"  value="1"/>

<?php 
function getAllChkboxValues($chk_name) {
    $found = array(); //create a new array 
    foreach($chk_name as $key => $val) {
        //echo "KEY::".$key."VALue::".$val."<br>";
        if($val == '1') { //replace '1' with the value you want to search
            $found[] = $key;
        }
    }
    foreach($found as $kev_f => $val_f) {
        unset($chk_name[$val_f-1]); //unset the index of un-necessary values in array
    }   
    final_arr = array(); //create the final array
    return $final_arr = array_values($chk_name); //sort the resulting array again
}
$chkox_arr = getAllChkboxValues($_POST['chk_name']); //Chkbox Values
echo"<pre>";
print_r($chkox_arr);
?>

Here's my solution:

With an array of checkboxes in the html like so...

<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />

I then fix the posted array with this function...

$_POST[ 'something' ] = $this->fixArrayOfCheckboxes( $_POST[ 'something' ] );
function fixArrayOfCheckboxes( $checks ) {
    $newChecks = array();
    for( $i = 0; $i < count( $checks ); $i++ ) {
        if( $checks[ $i ] == 'off' && $checks[ $i + 1 ] == 'on' ) {
            $newChecks[] = 'on';
            $i++;
        }
        else {
            $newChecks[] = 'off';
        }
    }
    return $newChecks;
}

This will give me an array with values of either 'on' or 'off' for each (and every) checkbox.

Note that the hidden input MUST be BEFORE the checkbox input in order for the function to work right.


Here's my solution:

<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>
<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>

Need Your Help

Visual Studio 2015 InvalidProgramException in Unit Test With Fakes

c# unit-testing visual-studio-2015 microsoft-fakes .net-4.6

I am using Visual Studio 2015 Enterprise RTM to write unit tests for a project that uses Unity Container.

Can't access index.gsp in grails

grails gsp grails-controller

I am new to grails and I am trying to access index page. After deleting the default homepage for grails, I getting the following error