This question already has an answer here:
I have checkboxes which change value using JavaScript and I want to store values of all checkboxes in a PHP array. But if the user changes the value of one checkbox to "0", the array created has only 2 values (1,1) instead of (1,0,1).
HTML
<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">
<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">
<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">
PHP
$wer=$_POST['cbox1'];
echo implode(",",$wer);
Jquery
$(document).on('click', '.chbo', function() {
this.value ^= 1;
console.log(this.value);
});
</div>
Only successful (checked) controls are submitted. You need to add a hidden input with the default value before the checkbox. Notice you need to hard code the indexes so that the hidden default matches the checkbox value:
<input type="hidden" name="cbox1[0]" value="0" class="chbo">
<input type="checkbox" name="cbox1[0]" value="1" class="chbo" checked="checked">
<input type="hidden" name="cbox1[1]" value="0" class="chbo">
<input type="checkbox" name="cbox1[1]" value="1" class="chbo" checked="checked">
So if not checked, only the hidden cbox1[0]
with value 0
will be submitted. If checked, then cbox1[0]
with value 1
will overwrite the hidden input.
You won't need the JavaScript now because you can change the checkbox to value 0
but if it is not checked it won't be submitted.
Unchecked checkboxes do not exist within the POST or GET array after form submission. To check for unchecked checkbox form elements, use a simple isset() call.
$wer[0]=isset($_POST['cbox1'][0]) ? $_POST['cbox1'][0]:0;
$wer[1]=isset($_POST['cbox1'][1]) ? $_POST['cbox1'][1]:0;
...