Hi,
I'm new, so please let me know if any of my forum etiquette is wrong! Apologies for the fairly nondescript subject line, but I am being driven insane by it.
Anyhow, I have a form with multiple checkboxes that need to be sticky, so I check the checkbox $_POST array against the array of form elements using a nested foreach loop. The trouble is, that when the form is submitted, even though all the checked boxes are in the $_POST array, only the final matching checkbox is checked.
Hopefully, this code will help:
The data:
The function to create the checkbox portion of the form:
Now, I imagine there's some coding horrors in there (like cleaning and escaping the POST data before use, which I promise I'll do!), and if you could point them out to me, I'd be most grateful.
What it's supposed to do (in my mind) is loop thorough the whole of the $areas array, then for each entry, loop through the $_POST array, see if there's a match, write "checked" into the html and start again. However, it doesn't, and I don't understand why.
Any help would be very much appreciated.
I'm new, so please let me know if any of my forum etiquette is wrong! Apologies for the fairly nondescript subject line, but I am being driven insane by it.
Anyhow, I have a form with multiple checkboxes that need to be sticky, so I check the checkbox $_POST array against the array of form elements using a nested foreach loop. The trouble is, that when the form is submitted, even though all the checked boxes are in the $_POST array, only the final matching checkbox is checked.
Hopefully, this code will help:
The data:
Code:
$areas = array("Brierley_Hill" => "Brierley Hill","Cradley_Heath" => "Cradley Heath", "Dudley" => "Dudley" ,"Gornal" => "Gornal","Halesowen" => "Halesowen","Kingswinford" => "Kingswinford","Netherton" => "Netherton","Oldbury" => "Oldbury","Pensnett" => "Pensnett","Quarry_Bank" => "Quarry Bank","Rowley_Regis" => "Rowley Regis","Stourbridge" => "Stourbridge","Tipton" => "Tipton","Tividale" => "Tividale");
Code:
function doTownCheckBoxes($areas){
foreach($areas as $value => $area){
foreach($_POST['Towns'] as $town){
$checked = ($town==$value) ? "checked" : "";
}
$html.= '<li><input type="checkbox" name="Towns[]" value="'.$value.'" '.$checked.'> '.$area.'</li>';
}
return $html;
}
What it's supposed to do (in my mind) is loop thorough the whole of the $areas array, then for each entry, loop through the $_POST array, see if there's a match, write "checked" into the html and start again. However, it doesn't, and I don't understand why.
Any help would be very much appreciated.
Comment