如何提交复选框的值?

时间:2013-08-03 19:01:13

标签: php html

在我的表格上我有这一部分:

<input type="checkbox" name="city" value="Nicosia" class="choosecity">Nicosia<br>
<input type="checkbox" name="city" value="Limassol" class="choosecity">Limassol<br>
<input type="checkbox" name="city" value="Larnaca" class="choosecity">Larnaca<br>

在我使用邮件功能的结果页面上,我希望获得已检查的城市。

我使用了这个没有结果:

foreach($_POST['city'] as $checkbox){
    echo $checkbox . ' ';
}

我在这里缺少什么?

4 个答案:

答案 0 :(得分:2)

使用name="city[]"。否则您只能提交一个城市。您可能还想使用

$cities = isset($_POST['city']) ? $_POST['city'] : array();
foreach ($cities as $city)

答案 1 :(得分:1)

您需要将输入命名为数组name="city[]"

答案 2 :(得分:1)

PHP使用方括号语法将表单输入转换为数组,所以当你使用name =“education []”时,你会得到一个数组:

$educationValues = $_POST['education']; // Returns an array
print_r($educationValues); // Shows you all the values in the array

例如:

<p><label>Please enter your most recent education<br>
    <input type="text" name="education[]"></p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]"></p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]"></p>

将在$ _POST ['education']数组中为您提供所有输入值。

在JavaScript中,通过id ...

获取元素效率更高
document.getElementById("education1");

id不必与名称匹配:

<p><label>Please enter your most recent education<br>
    <input type="text" name="education[]" id="education1"></p>

答案 3 :(得分:0)

您只需将此[]添加到输入名称,这将创建一个以[0]开头的数组。结果看起来如此:

array(
   [0] => 'Nicosia',
   [1] => 'Limassol',
   [2] => 'Larnaca',
)

HTML:

<input type="checkbox" name="city[]" value="Nicosia" class="choosecity" />Nicosia<br>
<input type="checkbox" name="city[]" value="Limassol" class="choosecity" />Limassol<br>
<input type="checkbox" name="city[]" value="Larnaca" class="choosecity" />Larnaca<br>

PHP:

if( isset($_POST[city]) && is_array($_POST[city]) ){
   foreach($_POST[city] as $checkbox){
       echo $checkbox . ' ';
   }
}