为了账号安全,请及时绑定邮箱和手机立即绑定

如何读取多个复选框(以及与之关联的数据)?

如何读取多个复选框(以及与之关联的数据)?

蝴蝶不菲 2023-03-03 10:29:20
我有一个带有多个复选框的表单,每个复选框作为与其关联的输入字段,一旦您选中该复选框就会激活。我的前端工作得很好,但我想知道如何在我的 PHP 中读取哪些复选框与其各自的输入字段一起被选中(有些除了输入字段外还有一个单选按钮)这是我表单中每个单独的复选框的样子: <!-- Option1 -->              <div class="form-row">                <div class="form-group col-md-8">                  <div class="form-check">                    <input class="form-check-input showman" type="checkbox" onchange="showqt()" value="Button Chicken Amritsari" id="c1">                    <label class="form-check-label" for="c1">                      Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>                    </label>                  </div>                </div>                  <div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">                    <!-- <label for="qtcounter">Quantity:</label> -->                    <div class="input-group" id="qtcounter">                      <input type="button" value="-" class="button-minus" data-field="quantity">                      <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">                      <input type="button" value="+" class="button-plus" data-field="quantity">                    </div>                  </div>              </div>              <!-- Option 1 ends -->我还没有完全了解 PHP,但之前为了读取多个复选框,我将它们全部放在字段中的一个数组中,name然后在 PHP 中读取该数组。但是,这并没有增加每个具有输入字段的复选框的复杂性。有谁知道如何做到这一点?
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

您希望对输入和复选框都使用关联数组。


<!-- Option1 -->

<div class="form-row">

  <div class="form-group col-md-8">

    <div class="form-check">

      <input class="form-check-input showman" type="checkbox" name="items[1][chosen]" onchange="showqt()" value="Button Chicken Amritsari" id="c1">

      <label class="form-check-label" for="c1">

        Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>

      </label>

    </div>

  </div>

    <div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">

      <!-- <label for="qtcounter">Quantity:</label> -->

      <div class="input-group" id="qtcounter">

        <input type="button" value="-" class="button-minus" data-field="items[1][quantity]">

        <input type="number" step="1" max="" value="1" name="items[1][quantity]" class="quantity-field">

        <input type="button" value="+" class="button-plus" data-field="items[1][quantity]">

      </div>

    </div>

</div>

<!-- Option 1 ends -->

对于选项 2,请使用items[2][chosen]anditems[2][quantity]等。


注意必须指定索引,不能使用[]. 否则, 的索引quantity将与所选项目不匹配。


在 php 中,您可以遍历项目并忽略未选择的项目。


foreach ($_POST['items'] as $item) {

    if (!isset($item['chosen'])) continue; // Skip items that aren't chosen.


    echo $item['quantity'] . ' ' . $item['chosen'] . "\n"; 

}


查看完整回答
反对 回复 2023-03-03
  • 1 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信