How to send all checkboxes whether checked or unch

2019-08-23 11:06发布

I have a form with multiple checkbox

<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />

So when i click the submit button in to submit the form it only sends the checked boxes.

I searched on the net and found that we can include hidden field above the real checkbox like so:

<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />

But when i do var_dump($request->group_checkbox) in Laravel Controllerit shows

array(10) { [0]=> string(1) "0" [1]=> string(1) "1" [2]=> string(1) "0" [3]=> string(1) "1" [4]=> string(1) "0" [5]=> string(1) "1" [6]=> string(1) "0" [7]=> string(1) "1" [8]=> string(1) "0" [9]=> string(1) "1" }

when all 5 checkboxes are checked.

and shows

array(5) { [0]=> string(1) "0" [1]=> string(1) "0" [2]=> string(1) "0" [3]=> string(1) "0" [4]=> string(1) "0" }

when no checkboxes are checked.

So why is it sending (0 and 1) when a checkbox is checked and not just 1 instead

1条回答
欢心
2楼-- · 2019-08-23 11:59

This is how PHP handles multiple values for parameters ending in []. If you want to overwrite the 0 value with a checked checkbox, you will need to explicitly name the index, otherwise PHP interprets it as values that should be appended to the array.

So, use either grouped_checkbox or grouped_checkbox[0].

Like this:

<input name="grouped_checkbox[0]" type="hidden" value="0">
<input name="grouped_checkbox[0]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->

<input name="grouped_checkbox[1]" type="hidden" value="0">
<input name="grouped_checkbox[1]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->

<!-- ... and so forth -->
查看更多
登录 后发表回答