Below is the code for my checkboxes, I have got a FOREACH loop which creates all the checkboxes. foreach ($cat as $index => $value) { echo '<input type="checkbox" name="selection[]" value="'.$cat[$index][2].'" id="'.$index.'"/>'.$cat[$index][2].'; } Code (markup): I've got some form processing going on that counts the number of checkboxes that are checked and if it is less than 3 then it redisplays the form with an error message. But I would like it to keep the checkboxes ticked too - how can this be acheived with the above code setup?
try this foreach ($cat as $index => $value) { $selected = ($_REQUEST['selection'][$index]) ? ' checked="checked"':''; echo '<input type="checkbox" name="selection[]" value="'.$cat[$index][2].$selected.'" id="'.$index.'"/>'.$cat[$index][2]; } PHP:
I've not used foreach when using lots of checkboxes - I number them instead with the id from the table in the database and check them afterwards with a while() loop. Build your checkboxes with a number on the end like this: <input type="checkbox" name="chk1" /> <input type="checkbox" name="chk2" /> <input type="checkbox" name="chk3" /> Code (markup): and so-on. Next use something like this to rebuild them: $row=mysql_query("SELECT data FROM table"); while ($row=mysql_fetch_assoc($query)) { echo '<input type="chechkbox" name="chk'.$row['id'].'"'.($_POST['chk'.$row['id']] ? ' checked="checked"' : '').' />'; } PHP:
Hi Yesideez, I'm not using a database, in fact I'm storing the menu data in an array $cat. Do u know how I can implement your solution using the variables I have used in my code above?
$arrSize=count($cat); for ($i=0;$i<$arrSize;$i++) { echo '<input type="checkbox" name="chk'.$i.'"'.($_POST['chk'.$i] ? ' checked="checked"' : '').' />'; } PHP: Try that and see how you go.