【问题标题】:In PHP how to Keep the values in the form for check box?在 PHP 中,如何将值保留在复选框的表单中?
【发布时间】:2019-12-20 21:59:06
【问题描述】:

这是我的 HTML 代码

<label>Subject : </label>
<label><input type="checkbox" name="subject" id="subject[]" value="Maths"/>Maths</label>
<label><input type="checkbox" name="subject" id="subject[]" value=English"/>English</label>
<label><input type="checkbox" name="subject" id="subject[]" value="Tamil"/>Tamil</label>

这是php代码

<label>
<input type="checkbox" name="subject" id="subject[]" <?php if (isset($_POST["subject"]) && $_POST["subject"]=="Maths") echo "checked";?> value = "Maths"/>Maths
</label>
<label>
<input type="checkbox" name="subject" id="subject[]" <?php if (isset($_POST["subject"]) && $_POST["subject"]=="English") echo "checked";?> value = "English"/>English
</label>
<label>
<input type="checkbox" name="subject" id="subject[]" <?php if (isset($_POST["subject"]) && $_POST["subject"]=="Tamil") echo "checked";?> value = "Tamil"/>Tamil
</label>

但不工作。

【问题讨论】:

  • 你的主题是一个数组^^不是一个字符串
  • 请不要覆盖提高问题可读性的编辑(改为添加到问题的编辑版本)
  • 当问题陈述很简单时,很难提供解决方案"it doesn't work"。请edit您的问题更完整地描述您预期会发生什么以及这与实际结果有何不同。请参阅 How to Ask 以获取有关什么是好的解释的提示。
  • 这能回答你的问题吗? PHP checkbox set to check based on database value

标签: php html checkbox


【解决方案1】:

如果您想将所有复选框都称为同名,那么它们需要是一个数组

<label>
<input type="checkbox" name="subject[]" id="subject[]" <?php if (isset($_POST["subject"][0]) && $_POST["subject"][0]=="Maths") echo "checked";?> value = "Maths"/>Maths
</label>
<label>
<input type="checkbox" name="subject[]" id="subject[]" <?php if (isset($_POST["subject"][1]) && $_POST["subject"][1]=="English") echo "checked";?> value = "English"/>English
</label>
<label>
<input type="checkbox" name="subject[]" id="subject[]" <?php if (isset($_POST["subject"][2]) && $_POST["subject"][2]=="Tamil") echo "checked";?> value = "Tamil"/>Tamil
</label>

【讨论】:

  • 抱歉,我修正了一个错字,现在看第二个和第三个&lt;input&gt;。都需要name="subject[]"
【解决方案2】:

这是正确的代码之一。

<label>Subject : </label>
            <label><input type = "checkbox" name = "subject[]" id = "subject" <?php echo (in_array("Maths",$_POST["subject"]))?"checked" : " "?> value = "Maths"/>Maths</label>
            <label><input type = "checkbox" name = "subject[]" id = "subject" <?php echo (in_array("Maths",$_POST["subject"]))?"checked" : " "?> value = "English"/>English</label>
            <label><input type = "checkbox" name = "subject[]" id = "subject" <?php echo (in_array("Maths",$_POST["subject"]))?"checked" : " "?> value = "Tamil"/>Tamil</label>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2012-01-06
    相关资源
    最近更新 更多