是的。这让我心碎。我发现了很多关于这个特定主题的教程,但似乎没有什么对我有用。我一定是错过了一些我找不到的东西。
如果表单中存在先前的错误,我只是想保持选中的复选框处于选中状态。我的验证在所有字段上都运行得很好,但我需要保留复选框,但我无法解决这个问题。
以下是我正在使用的片段:
这会检查 $data[id] isset()
<input name="seminar[]" type="checkbox" id="seminar[]"
value="
<?php
if(isset($data['id'])) {
$checked = "checked=\"checked\"";
} else {
echo "";
}
?>
" <?php echo "$checked"; ?>>
我什至检查了我的 html 源代码,这就是提交后显示的内容:
<input name="seminar[]" type="checkbox" id="seminar[]" value="" checked="checked">
如您所见value="" 是空的!,所以在我上面的脚本中它应该回显“”,但这不起作用。
事实上,当我清除缓存并重新加载表单时,所有框都被选中!?
谁能看到我做错了什么。也许我在这里翻错了石头……不知道,但将近 4 个小时的时间付诸东流,我放弃了白旗。
Yup. This one is tearing me up. I found a lot of tutorials on this specific subject, but nothing seems to be working for me. I must be missing something which I cannot find.
I am simply trying to keep selected checkboxes checked if there is a previous error in the form. My validation is working totally fine with all fields, but I need to retain the checked boxes and I just can't solve this.
Here are the snippets I am working with:
This checks if the $data[id] isset()
<input name="seminar[]" type="checkbox" id="seminar[]"
value="
<?php
if(isset($data['id'])) {
$checked = "checked=\"checked\"";
} else {
echo "";
}
?>
" <?php echo "$checked"; ?>>
And I even checked in my html source, and this is what is showing after submission:
<input name="seminar[]" type="checkbox" id="seminar[]" value="" checked="checked">
As you can see value="" is empty!, so in my script above it should echo "", but that's not working.
As a matter of fact, when I clear the cache and reload the form all boxes are just checked!?
Can anyone see what I am doing wrong. Maybe I am turning over the wrong stones here.. Dunno, but nearly 4 hours down the drain and I'm waiving a white flag.
发布评论
评论(1)
我发现有几个问题可能会导致您的问题。
首先,您会被分配
研讨会[]
复选框的名称
。这将创建一个数组,其中包含使用该名称的所有复选框的值。由于您没有在[]
之间指定键,因此它会自动为您执行此操作。您应该自己指定某种密钥,以便稍后可以将它们匹配。示例:
然后您可以通过执行以下操作检查它是否已设置:
其次,您不能使用
seminar[]
作为复选框的ID
。看看我上面的例子,你可以找到另一种方法。 ID在页面上必须是唯一的;您不能在一个页面上两次使用相同的 ID。第三,这个
$data['id']
到底是什么?您应该检查$_POST
值以获取项目的确切名称。再次看我的第一个例子。我会重新格式化您的代码,使其看起来像这样:
I see several things wrong that could possibly be contributing to your problem.
First, you're assigned the
name
of the checkboxseminar[]
. This creates an array with values from all checkboxes that use that name. Since you're not specifying a key in between the[]
, it automatically does this for you. You should specify some sort of key yourself so you can match them up later.Example:
Then you can check if it's set by doing this:
Second, you can't use
seminar[]
for theID
of the checkbox. Look at my above example for an alternative way you can do it. IDs have to be unique on the page; You cannot use the same ID twice on a single page.Third, what is this
$data['id']
exactly? You should be checking the$_POST
value for the exact name of the item. Again, look at my first example.I'd reformat your code to look something like this: