从多个复选框获取开机自检数据?

2022-08-30 22:46:37

我试图使用PHP创建一个表单,我似乎找不到我需要什么的教程,所以认为Id在这里问。

我的页面上有多个复选框选项...

 <li>
    <label>What service are you enquiring about?</label>
    <input type="checkbox" value="Static guarding" name="service">Static guarding<br>
    <input type="checkbox" value="Mobile Patrols" name="service">Mobile Patrols<br>
    <input type="checkbox" value="Alarm response escorting" name="service">Alarm response escorting<br>
    <input type="checkbox" value="Alarm response/ Keyholding" name="service">Alarm response/ Keyholding<br>
    <input type="checkbox" value="Other" name="service">Other<input type="hidden" value="Other" name="service"></span>
  </li>

我不确定如何使用POST方法收集所有复选框值?

如果我使用

$service = $_POST['service'];

我只得到“其他”返回


答案 1

将字段命名为 而不是 ,然后您就可以将其作为数组进行访问。之后,您可以将常规函数应用于数组:service[]service

  • 检查是否选择了某个值:

     if (in_array("Other", $_POST['service'])) { /* Other was selected */}
    
  • 获取包含所有选定选项的单个换行符分隔字符串:

     echo implode("\n", $_POST['service']);
    
  • 遍历所有选定的复选框:

     foreach ($_POST['service'] as $service) {
         echo "You selected: $service <br>";
     }
    

答案 2

目前,它只是捕获您上次隐藏的输入。你为什么会有隐藏的输入呢?如果要在选中“其他”框时收集信息,则必须隐藏

<input type="text" name="other" style="display:none;"/> 

并且您可以在选中“其他”框时使用javascript显示它。类似的东西。

只需使名称属性服务[]

<li>
<label>What service are you enquiring about?</label>
<input type="checkbox" value="Static guarding" name="service[]">Static guarding<br />
<input type="checkbox" value="Mobile Patrols" name="service[]">Mobile Patrols<br />
<input type="checkbox" value="Alarm response escorting" name="service[]">Alarm response escorting<br />
<input type="checkbox" value="Alarm response/ Keyholding" name="service[]">Alarm response/ Keyholding<br />
<input type="checkbox" value="Other" name="service[]">Other</span>
</li>

然后在您的PHP中,您可以像这样访问它

$service = $_POST['service'];
echo $service[0]; // Output will be the value of the first selected checkbox
echo $service[1]; // Output will be the value of the second selected checkbox
print_r($service); //Output will be an array of values of the selected checkboxes

等。。。


推荐