I have a set of checkboxes which when checked they pass the value as 1, otherwise they pass the value as 0. However, instead of sending the value of the unchecked checkboxes as '0', the value being sent is 'NULL'.
I have the following JS code in place that should set the value to 0/1 accordingly, however still the value is sent as NULL. Is there anything that can be done to make sure that the value passed in case of an unchecked checkbox is 0?
$('#cb1, #cb2, #cb3, #cb4').on('click', function ()
$(this).val(this.checked ? 1 : 0);
<input type="checkbox" name="cb1" id="cb1" value="1" checked />
<input type="checkbox" name="cb2" id="cb2" value="1" checked />
<input type="checkbox" name="cb3" id="cb3" value="1" checked />
<input type="checkbox" name="cb4" id="cb4" value="1" checked />
If a checkbox is unchecked, it doesn't get sent, so setting it's value to 0 if it isn't checked isn't going to help - it will always return NULL.
There are two ways to fix this easily:
1) Assume a NULL in the PHP params means the checkbox is unchecked. If the checkbox doesn't always exist on the page, this could be problematic. By the sounds of it, there is a variable number of checkboxes, so this probably won't work.
2) Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.
<input type="hidden" name="checkbox_1" value="0"> <input type="checkbox" name="checkbox_1" value="1">
Note: If your names are in an array form (ie they have square brackets in them), this won't work, as the hidden fields will increment the array count as well.