Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
                });

            });
share|improve this question
    
Unchecked checkboxes are NOT submitted with the rest of the form. If you want "no", you'd have to keep track of which checkboxes are on the form and make a list of which ones weren't checked. The alternative is some javascript at submit time to loop over all the checkboxes and build up a list of unchecked ones and submit that value as another form field. –  Marc B Jun 16 '11 at 18:03
    
Suggest making each new row 'checked' by default by adding the 'checked' attribute so it's less likely that the user will submit an unchecked row. <input type="checkbox" name="mailing[]" value="" checked /> –  gne00 Jun 16 '11 at 18:18

4 Answers 4

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.

share|improve this answer

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);
?>
share|improve this answer

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
share|improve this answer
    
@AJ Not sure how I would do that, as subsequent rows on the form are added dynamically using cloning. –  Nick Jun 16 '11 at 17:45
    
Updated my answer...you can't do that? (above) –  AJ. Jun 16 '11 at 17:48
    
@AJ No, it's not clear to me how I would generate unique values using the cloning method. I have added the form and cloning script to my question above. –  Nick Jun 16 '11 at 17:53
1  
That's not really how checkboxes work...if it's not checked, it doesn't get sent to the server. If you need to know explicitly which checkboxes are unchecked, you'll have to implement another mechanism to do this. There are different techniques, one of which is to use a hidden field for each checkbox. See this link: planetozh.com/blog/2008/09/… –  AJ. Jun 16 '11 at 18:07
1  
I think you could assign a different value to each checkbox. I'll update my answer with the code. –  AJ. Jun 16 '11 at 18:38
$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);
share|improve this answer
    
Thanks. Would this method work with the cloning method I am using to dynamically add rows? –  Nick Jun 16 '11 at 17:48
    
@Nick: As long as you keep some sort of running index and increment it anytime you dynamically add a row and decrement it when you remove one). You would need to send the script the total number of checkboxes and modify my code a bit to use a number of checkboxes instead of a list. –  GWW Jun 16 '11 at 17:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.