如何同时获取多个选中的复选框ID和VALUE

问题描述 投票:0回答:2

如何通过POST同时获取多个选中的复选框ID和VALUE?代码bellow显示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并通过邮件获取它们而不会爆炸?我肯定可以将它们分开,但应该有另一种方式。

php html post checkbox
2个回答
1
投票

如果要从输入中获取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=>value

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

4
投票

你可以这样做:

<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/>';
}
© www.soinside.com 2019 - 2024. All rights reserved.