【发布时间】:2014-03-26 16:19:25
【问题描述】:
我在表单中有一些同名的字段,它们是从数据库表中自动生成的,我不知道会有多少。
<div class="row w40 fl">
<label for="code" class="label">codice <span class="form-notice">*</span></label>
<input type="text" class="input" name="code" id="code" placeholder="Codice" value="<?= Input::post('code') ?>">
</div>
<div class="row w40 fr">
<label for="name" class="label">nome <span class="form-notice">*</span></label>
<input type="text" class="input" name="name" id="name" placeholder="Nome" value="<?= Input::post('name') ?>">
</div>
<?php foreach($categories as $cat): ?>
<div class="w20 fl">
<label for=""><?= ucwords($cat->name) ?></label>
<input type="checkbox" name="cat[]" value="<?= $cat->id ?>" <?= ($cat->id == Input::post('cat')) ? 'checked' : '' ?>>
</div>
<?php endforeach; ?>
问题是如果提交后出现错误,所有勾选的输入都会丢失。如果它们有不同的名称,那不会有任何问题,但它们总是不同的。
那么在提交之后,我如何才能记住选中的并检查它们呢?假设用户检查了其中的 5 个,填写了所有表单输入但留下一个空白。显然会弹出一个错误,但是虽然所有其他输入都会有用户输入的数据,但复选框不会,至少我不知道该怎么做。
注意Input::post('code') 表示(isset($_POST['code'])) ? $_POST['code'] : ''
谢谢你,希望你能给我一个解决方案。
好的,经过更多研究,这里是解决方案。
if ( isset($_POST['cat']) ) {
foreach ($_POST['cat'] as $cbCat) {
$selectedCat[$cbCat] = 'checked';
}
}
<?php foreach($categories as $cat): ?>
<div class="w20 fl">
<label for="cat-<?= $cat->id ?>"><?= ucwords($cat->name) ?></label>
<input type="checkbox" id="cat-<?= $cat->id ?>" name="cat[]" value="<?= $cat->id ?>" <?= (isset($selectedCat[$cat->id])) ? $selectedCat[$cat->id] : '' ?> >
</div>
<?php endforeach; ?>
【问题讨论】:
标签: php html post checkbox form-submit