user1809790 user1809790 - 1 year ago 222
HTML Question

Unchecked checkbox returning null value

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);

Here is my html:

<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 />

They are all checked by default.

If one of them is unchecked, MySQL is reporting the following error:
0SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'ColumnName' cannot be null.

This is because the columns are set to set not to be Null. And even though I have set the default value to 0, once I click on the submit button I still get the error. I tried to remove the Not NULL property however rather than prefilling the value as 0, the input was NULL in the database.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download