我有以下带有复选框的表单。
<?php
include 'connection.php';
$sql="SELECT * FROM `tbl`";
$query=mysqli_query($connect,$sql);
echo "<table border='2px'>
<thead>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</thead>
<tbody>
<form method='POST'>";
while($res=mysqli_fetch_assoc($query)){
$id=$res['id'];
echo"<tr>
<td>{$res['id']}</td>
<td>{$res['title']}</td>
<td>{$res['name']}</td>
<td><input type='checkbox' name='doing[]' value='".$res['id'].$res['title'].$res['name']."'></td>
<td><input type='checkbox' name='done[]' value='".$res['id'].$res['title'].$res['name']."'></td>
</tr>";
}
echo "<input type='submit' value='OK' name='btn'>
</form>
</tbody>
</table>";
?>
如何在提交表单时使复选框保持选中
状态?
最佳答案
我假设您不希望同时检查 doing
和 done
,因此我用单选按钮替换了复选框,因为这是它们的预期目的行为。
我更改了单选按钮的名称和值,以便可以在 PHP 中轻松访问它们,并且从您提供的代码来看,它看起来并不像是您之后使用的名称和值。
我清理了标记和脚本布局以使其更具可读性。
如果我与原始代码的意图相差太远,请告诉我。
注意:这将显示发布的值,但不会将这些值保存到数据库中。
( Demo )
<?php
include('connection.php');
$sql = "SELECT * FROM `tbl`";
$query = mysqli_query($connect,$sql);
function get_checked ( $id ) {
if ( isset($_POST) && isset($_POST['checked'][$id]) ) {
return $_POST['checked'][$id];
}
return false;
}
?>
<form method="post">
<table border="2px">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<?php while ( $res = mysqli_fetch_assoc ( $query ) ): ?>
<?php $checked = get_checked ( $res['id'] ) ?>
<tr>
<td><?= $res['id'] ?></td>
<td><?= $res['title'] ?></td>
<td><?= $res['name'] ?></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="doing" <?= $checked === "doing" ? 'checked' : '' ?>></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="done" <?= $checked === "done" ? 'checked' : '' ?>></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<input type='submit' value='OK' name='btn'>
</form>
关于javascript - 提交表单时保持选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882942/