【问题标题】:How to submit the values of checkbox? [duplicate]如何提交复选框的值? [复制]
【发布时间】:2013-08-04 20:47:12
【问题描述】:

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

<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 . ' ';
}

我在这里错过了什么?

【问题讨论】:

  • 您的表单名称需要使用数组语法,然后使用&lt;input name="city[]"&gt;

标签: php html


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      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>
      

      【讨论】:

        【解决方案4】:

        您只需将此[] 添加到输入名称,这将创建一个以[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 . ' ';
           }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-26
          • 1970-01-01
          • 2014-08-27
          • 2012-11-11
          • 1970-01-01
          • 1970-01-01
          • 2015-08-24
          • 1970-01-01
          相关资源
          最近更新 更多