【问题标题】:How to get multiple checked checkbox ID and VALUE at the same time如何同时获取多个选中的复选框 ID 和 VALUE
【发布时间】:2017-12-19 22:25:12
【问题描述】:

如何通过 POST 多个选中的复选框 ID 和 VALUE 同时获得?下面的代码显示了发送数据的 html。

<form action="" method="post">
  first<input type="checkbox" name="first[]" id="first'<?php echo $data; ?>'" value="first" />
  second<input type="checkbox" name="first[]" id="second'<?php echo $data2; ?>'" value="second" />
  third<input type="checkbox" name="first[]" id="third'<?php echo $data3; ?>'" value="third" />
  <input type="submit" value="submit">
</form>

通过邮局发送后,我得到了值,但缺少 ID。

foreach($_POST['first'] as $value){
  echo 'VALUE: '.$value.'<br/>';
}

如何发送 ID 和 VALUE 并通过邮寄方式获取它们而不会爆炸?当然我可以在之后拆分它们,但应该有另一种方法。

【问题讨论】:

  • id 未发送到服务器。您实际上想在这里实现什么目标?为什么?
  • 一个元素的ID不会传到后端。您必须添加一个专用的&lt;input type="hidden"&gt; 并将其值设置为 ID 的值。
  • 如果 id 与 value 相同 - 有什么意义?
  • 另外,我不认为first[] 是 HTML 中的有效 ID。
  • 如果你想要id,然后将其添加到名称数组中 -> name="first[first]"/name="first[second]"/name="first[third]"name="first[1]"/name="first[2]"/name="first[3]"。然后你可以在你的循环中得到它 -> foreach($_POST['first'] as $id =&gt; $value){ echo 'ID: '.$id.' VALUE: '.$value.'&lt;br/&gt;'; }

标签: php html post checkbox


【解决方案1】:

你可以这样做:

<form action="" method="post">
  first<input type="checkbox" name="first[0][value]" id="first[]" value="first" />
  <input type="hidden" name="first[0][id]" value="first[]">
  second<input type="checkbox" name="first[1][value]" id="second[]" value="second" />
  <input type="hidden" name="first[1][id]" value="second[]">
  third<input type="checkbox" name="first[2][value]" id="third[]" value="third" />
  <input type="hidden" name="first[2][id]" value="third[]">
  <input type="submit" value="submit">
</form>

在后端:

foreach($_POST['first'] as $value){
  echo 'VALUE: '.$value['value'].'<br/>';
  echo 'ID: '.$value['id'].'<br/>';
}

【讨论】:

  • 现在我明白你的意思了)这个也为我工作!)谢谢!)
  • @Orik0 不客气。老实说,我希望您不要在您的项目中使用我的示例,因为这应该仅作为最后的手段使用,但我确实希望我能够向您展示一些关于 HTML/PHP 中的数组的新内容。祝你好运!
  • 我用了不同的方式,但你的方式对我来说是新的,谢谢你展示新的方式!)
【解决方案2】:

如果您想从输入中获取 id 值,请使用 id 作为名称数组中的键

<input type="checkbox" name="first[first]" .../>
<input type="checkbox" name="first[second]" .../>
<input type="checkbox" name="first[third]" .../>

<input type="checkbox" name="first[1]" .../>
<input type="checkbox" name="first[2]" .../>
<input type="checkbox" name="first[3]" .../>

然后,当您遍历您发布的输入时,将key 包含在key=&gt;value

foreach($_POST['first'] as $id => $value){ 
    echo 'ID: '.$id.' => VALUE: '.$value.'<br/>';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2020-02-28
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多