Keeping checkboxes checked in PHP form

Deadly 提交于 2019-12-04 16:54:23

A quick and dirty solution would be:

<input name="tape[]"  id="tape[]" type="checkbox" value="NA" <?php if(isset($_POST['tape']) && is_array($_POST['tape']) && in_array('NA', $_POST['tape'])) echo 'checked="checked"'; ?> />

For that you need to change the 'NA' part for each different answer obviously. Though I would look at something like having a loop for repeated checkboxes or a callback function to determine whether or not to echo checked=checked.

Thank you Mr. Code Here's my final code that I was able to figure out thanks to you

$mailBody .= "They requested additional information on ...\n\n";
$mailBody .= $moreinfo = join("\n", $_REQUEST["moreinfo"]);
$mailBody .= "\n\n";
$mailBody .= "They also had this to say...\n\n";
$mailBody .= "$comments\n\n";

//code on page

<input type="checkbox" name="moreinfo[selection1]" value="selection1" <?php if(isset($_POST['moreinfo']) && is_array($_POST['moreinfo']) && in_array('selection1', $_POST['moreinfo'])) echo 'checked="checked"'; ?> />  Selection 1<br>

<input type="checkbox" name="moreinfo[selection2]" value="selection2" <?php if(isset($_POST['moreinfo']) && is_array($_POST['moreinfo']) && in_array('selection2', $_POST['moreinfo'])) echo 'checked="checked"'; ?> />  Selection 2<br>

<input type="checkbox" name="moreinfo[selection3]" value="selection3" <?php if(isset($_POST['moreinfo']) && is_array($_POST['moreinfo']) && in_array('selection3', $_POST['moreinfo'])) echo 'checked="checked"'; ?> />  Selection 3<br>

I do not care that this looks crazy because it works.

You dont need to have the same name for checkboxes, only for radio buttons.

Radio buttons belong to a group so they have to have the same name but different values. Checkboxes however, can have different names for each checkbox! Therefore just change each checkbox to a differnent name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!