【问题标题】:How do I use the checkbox type of input in PHP correctly如何在 PHP 中正确使用复选框类型的输入
【发布时间】:2021-08-10 00:15:08
【问题描述】:

我希望下面的代码显示所有选中的复选框并限制为 2 个复选框。

输入

<form method="post" action="Outputofinfo.php">
   <b style="font-size:19px ; color: #7a1ac4; font: Arial,tahoma,sans-serif; ">Favourite Movie Genre:</b><br>
   
    <input type="checkbox" name="mg" value="Romance">
 <label for="mg1"> Romance</label><br>
 <input type="checkbox" name="mg" value="Comedy">
 <label for="mg2"> Comedy</label><br>
 <input type="checkbox" name="mg" value="Horror">
 <label for="mg3"> Horror</label><br>
 <input type="checkbox" name="mg" value="Action">
 <label for="mg4"> Action</label><br>
 <input type="checkbox" name="mg" value="Fiction">
 <label for="mg5"> Fiction</label><br>

 <input type="submit">
</form>

输出

$fmg = $_POST['mg'];
<div style ='font:21px Arial,tahoma,sans-serif;color:#7a1ac4'>
    <b>Favourite Movie Genre:</b>
    <?php echo $fmg; ?>
</div>

【问题讨论】:

  • 使用name="mg[]" 然后$_POST["mg"] 将是一个数组。必须使用 JavaScript 来限制复选框的数量

标签: php html forms


【解决方案1】:

[] 添加到name 属性(name=mg[]) 的末尾可以将一组值发送到服务器。您可以简单地访问服务器端的阵列。例如,您可以访问它的第一个元素,例如:$_POST['mg'][0]。 通过使用foreach,您可以访问所有选中的复选框。 或者你可以使用这样的东西:

$fmg = implode(", ", $_POST['mg']);

并根据需要向用户显示$fmg。 您的代码将是:

<form method="post" action="Outputofinfo.php">
   <b style="font-size:19px ; color: #7a1ac4; font: Arial,tahoma,sans-serif; ">Favourite Movie Genre:</b><br>
   
    <input type="checkbox" name="mg[]" value="Romance">
 <label for="mg1"> Romance</label><br>
 <input type="checkbox" name="mg[]" value="Comedy">
 <label for="mg2"> Comedy</label><br>
 <input type="checkbox" name="mg[]" value="Horror">
 <label for="mg3"> Horror</label><br>
 <input type="checkbox" name="mg[]" value="Action">
 <label for="mg4"> Action</label><br>
 <input type="checkbox" name="mg[]" value="Fiction">
 <label for="mg5"> Fiction</label><br>

 <input type="submit">
</form>

输出:

$fmg = implode(",",$_POST['mg']);
<div style ='font:21px Arial,tahoma,sans-serif;color:#7a1ac4'>
    <b>Favourite Movie Genre:</b>
    <?php echo $fmg; ?>
</div>

【讨论】:

  • 你能重复我的代码并添加你所说的@Sohrab
  • 请立即查看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 2020-01-30
  • 1970-01-01
相关资源
最近更新 更多