猿问

在 PHP 中,如何将值保留在复选框的表单中?

这是我的 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>

但不工作。


慕码人8056858
浏览 144回答 2
2回答

慕妹3146593

这是正确的代码之一。<label>Subject&nbsp;:&nbsp;</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label><input&nbsp;type&nbsp;=&nbsp;"checkbox"&nbsp;name&nbsp;=&nbsp;"subject[]"&nbsp;id&nbsp;=&nbsp;"subject"&nbsp;<?php&nbsp;echo&nbsp;(in_array("Maths",$_POST["subject"]))?"checked"&nbsp;:&nbsp;"&nbsp;"?>&nbsp;value&nbsp;=&nbsp;"Maths"/>Maths</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label><input&nbsp;type&nbsp;=&nbsp;"checkbox"&nbsp;name&nbsp;=&nbsp;"subject[]"&nbsp;id&nbsp;=&nbsp;"subject"&nbsp;<?php&nbsp;echo&nbsp;(in_array("Maths",$_POST["subject"]))?"checked"&nbsp;:&nbsp;"&nbsp;"?>&nbsp;value&nbsp;=&nbsp;"English"/>English</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label><input&nbsp;type&nbsp;=&nbsp;"checkbox"&nbsp;name&nbsp;=&nbsp;"subject[]"&nbsp;id&nbsp;=&nbsp;"subject"&nbsp;<?php&nbsp;echo&nbsp;(in_array("Maths",$_POST["subject"]))?"checked"&nbsp;:&nbsp;"&nbsp;"?>&nbsp;value&nbsp;=&nbsp;"Tamil"/>Tamil</label>

青春有我

如果您想将所有复选框称为同名,则它们需要是一个数组<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>
随时随地看视频慕课网APP
我要回答