使用php获取多个复选框名称/ ID [英] getting multiple checkboxes names/id's with php

查看:165
本文介绍了使用php获取多个复选框名称/ ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHP获取提交时多个选中的复选框的名称或ID?以下是示例表单。感谢。

How can i get the names or id's of the multiple selected checkboxes on submit, using the PHP? Following is example form. Thanks.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
   <input type="checkbox" name="orange" id="orange">
   <input type="checkbox" name="apple" id="apple">
   <input type="checkbox" name="sky" id="sky">
   <input type="checkbox" name="sea" id="sea">
   <br>
   <br>
   <input type="submit" name="Submit" value="Submit">
</form>


推荐答案

选择。

有几种方法可以处理PHP中的复选框:

There are several ways of handling checkboxes in PHP:


  1. 给所有复选框相同的名称,后跟一对方括号,因此整个集合被视为数组。

  2. 为每个复选框指定不同的名称,但是每个复选框的值必须不同。没有值。

在每种情况下,您都需要检查$ _POST数组中是否存在复选框名称。

In each case, you need to check for the existence of the checkbox name in the $_POST array.

例如:

<input type="checkbox" name="color[]" id="orange" value="orange">
<input type="checkbox" name="color[]" id="apple" value="apple">

要获取这些复选框的值:

To get the values for these checkboxes:

if (isset($_POST['color'])) {
    $colors = $_POST['color'];
    // $colors is an array of selected values
}

如果每个复选框都有不同的名称和显式值,如下所示:

However, if each checkbox has a different name and an explicit value like this:

<input type="checkbox" name="orange" id="orange" value="orange">
<input type="checkbox" name="apple" id="apple" value="apple">

您仍然需要使用isset():

You still need to use isset():

if (isset($_POST['orange'])) {
    // orange has been set and its value is "orange"
}

如果不设置值,默认值为on,但不会在$ _POST数组中,除非它被选中,所以你仍然需要使用isset()。

If you don't set a value, the default value is "on", but it won't be in the $_POST array unless it has been selected, so you still need to use isset().

这篇关于使用php获取多个复选框名称/ ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆