我要求未选中复选框的值为' 0'所以我可以确定已经检查了哪些值以及要发布的所有值(选中+未选中)($ _POST [' chk])。我正在使用for循环来创建复选框,我正在生成一个隐藏字段,其值为' 0' (正如在stackoverflow上建议elsewhere)。
有4个复选框((count($ result)-1)= 4)和复选框1&复选框2& 4未经检查,$ _POST [' chk']数组最终结果如下:
Array
(
[chk] => Array
(
[0] => 0
[1] => 180.00
[2] => 0
[3] => 0
[4] => 100.00
[5] => 0
)
我希望它看起来像这样:
Array
(
[chk] => Array
(
[0] => 180.00
[1] => 0
[2] => 100.00
[3] => 0
)
我做错了什么?甚至可以使用for循环和隐藏的复选框字段吗?
使用Javascript:
<script type="text/javascript">
function calculate() {
var el, i = 0;
var subtotal = 0;
while(el = document.getElementsByName("chk[]")[i++]) {
if(el.checked) { subtotal = subtotal + Number(el.value);}
}
var node = document.getElementById("subtotal");
node.innerHTML = "$" + subtotal + ".00";
var node = document.getElementById("total");
node.innerHTML = "$" + (subtotal*<?=$no_nights?>) + ".00";
}
</script>
HTML / PHP:
<form id="booking_step2" name="booking_step2" method="POST" action="index.php?p=bookings?s=3">
<? for ($x=0; $x<=(count($result)-1); $x++) { ?>
<input type="hidden" name="chk[]" value="0">
<input type="checkbox" name="chk[]" value="<?=$result[$x]['r_rate'];?>" onclick="calculate()">
<? } ?>
答案 0 :(得分:1)
您错误地使用chk[]
作为控件的名称。对于每个未选中的框,这将在$_POST
内为您提供一个元素,但对于每个已选中的框,将为两个元素。额外的元素可能存在于数组中的任何位置,因此您无法理解它。
而不是这样,为每对隐藏输入和复选框明确指定相同的索引:
<? for ($x=0; $x<=(count($result)-1); $x++): ?>
<input type="hidden" name="chk[<?=$x?>]" value="0">
<input type="checkbox" name="chk[<?=$x?>]" value="<?=$result[$x]['r_rate'];?>">
<? endfor; ?>
执行此操作后,复选框将与其前面的隐藏输入具有完全相同的名称chk[N]
,因此它将简单地胜过该值而不是在数组末尾添加另一个值。