Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make checkbox appear in $_POST array even if unchecked

Tags:

html

forms

php

I have an invoice in a HTML table. You select item name then item lot and the item #. There is a check box at the end to mark if it is sold out.

<input type="checkbox" name="soldout[]">

When I process the form the $_POST array of check boxes obviously don't contain the unchecked boxes. That leads me to problems when matching up the check boxes to the item

foreach($productID as $key=>$id){
    $p = $id;
    if(isset($soldout[$key])){
        $so = true;
    }
}

So if I have three line items and the first and last are marked sold out it processes as the first 2 sold out and the last one not sold out.

I don't think i can do this:

<input type="checkbox" name="soldout[<?php echo $i; ?>]">

because I am adding empty invoice lines with javascript when needed and wouldn't know how to increment the array key.

Any ideas on how to handle this?

like image 476
Casey Avatar asked Jan 27 '26 11:01

Casey


2 Answers

When you increase the array using JS just change the name to soldout_new and then increase a variable.

Something like this:

var soldout_new = 0;

function add()
{
'<input type="checkbox" name="soldout_new[' + soldout_new + ']">';

soldout_new += 1;
}

or also you can just set the variable to the id from php:

var soldout = <?php echo $i; ?>;

function add()
{
'<input type="checkbox" name="soldout[' + soldout + ']">';

soldout += 1;
}

There is no straight HTML solution for this. If Javascript is an option, you could look there, but if you want a straight HTML solution, an unchecked checkbox isn't going to show up in PHP, but a radio button will.

<input type="radio" name="soldout[<?php echo $i; ?>]" value="true"> Yes
<input type="radio" name="soldout[<?php echo $i; ?>]" value="false"> No

Then in PHP you can access it like

foreach($productID as $key=>$id){
    $p = $id;
    if($soldout[$key] == "true"){
        $so = true;
    }
    else {
        $so = false;
    }
}

Just remember the quotes around "true" because it's a string


Then again, if you are populating the checkboxes server-side you should also presumably know which values should exist and if they are not present in $_POST, assume they are unchecked.

foreach ($availableProductIDs as $id) {
    if(isset($_POST['soldout'][$id]){
        $so = true;
    }
    else {
        $so = false;
    }
}
like image 24
Mike Avatar answered Jan 30 '26 01:01

Mike