我试图在提交表单时保留复选框的输入值。
答案 0 :(得分:0)
当你选择多个时,你需要在复选框中使用数组。
1在输入复选框中使用name="filling[]"
。
2在foreach循环中使用$filling
来填充数据。
PHP代码
<?php
//echo '<pre>'.print_r($_POST,true).'</pre>';
$display_result = false;
$form_data = [
'filling' => [
'value' => [],
'error' => false,
'err_msg' => '',
],
];
if ( isset( $_POST['submit'] ) ) {
$filling = isset($_POST['filling'] ) ? $_POST['filling'] : '' ;
if( empty($filling) || count($filling) < 2 ) {
$form_data['filling']['error'] = true;
$form_data['filling']['err_msg'] = "Please select atleast 2 fllings";
}
else {
foreach ($filling as $value) {
array_push($form_data['filling']['value'], $value);
}
//$form_data['filling']['value'] = $filling;
$form_data['filling']['error'] = false;
}
}
?>
HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cake ordering Form</title>
<style>
.reqd {
color: red;
}
</style>
</head>
<body>
<form action="" method="post" id="cakeForm">
<fieldset>
<p>
<label>Fillings: <span class="reqd"><?php print
$form_data['filling']['error'] ? $form_data['filling']['err_msg'] : ''; ?></span></label><br />
<label class="checkFill"><input type="checkbox" name="filling[]" value="lemon" <?php print in_array('lemon', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Lemon <br /></label>
<label class="checkFill"><input type="checkbox" name="filling[]" value="custard" <?php print in_array('custard', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Custard <br /></label>
<label class="checkFill"><input type="checkbox" name="filling[]" value="fudge" <?php print in_array('fudge', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Fudge <br /></label>
<label class="checkFill"><input type="checkbox" name="filling[]" value="mocha" <?php print in_array('mocha', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Mocha <br /></label>
<label class="checkFill"><input type="checkbox" name="filling[]" value="raspberry" <?php print in_array('raspberry', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Raspberry <br /></label>
<label class="checkFill"><input type="checkbox" name="filling[]" value="pineapple" <?php print in_array('pineapple', $form_data['filling']['value'] ) ? 'checked = "checked" ' : ''; ?>/>Pineapple <br /></label>
</p>
</fieldset>
<p>
<input type="submit" value="submit" name="submit" />
</p>
</form>
</body>
</html>