Posting both checked and unchecked checkboxes

checkbox, jquery, php, webforms

Solution

You don't have to hide one of the checkboxes. Here is a solution that should accomplish what you want:

<input type="hidden" name="required" value="false" />
<input type="checkbox" name="required" value="true" />

If the checkbox is not checked, then the hidden field will be submitted with the `false` value. If the checkbox is checked, then the `true` value from the checkbox will override the `false` value from the hidden input.

As long as you can name each checkbox something slightly different, it should work.

The following should work as well for an array of values:

<input type="hidden" name="required[0]" value="false" />
<input type="checkbox" name="required[0]" value="true" />

<input type="hidden" name="required[n]" value="false" />
<input type="checkbox" name="required[n]" value="true" />

This way, you don't need any client side javascript to toggle the hidden checkboxes.

Problem

I'm trying to make a series of checkboxes in a web form that will post either "true" or "false" to the next php page, depending on whether they are checked. I decided that for each checkbox (value="true"), I would have a hidden checkbox (value="false") that would always be the opposite (when checkbox is checked, hidden checkbox is unchecked etc.) I am using jQuery to do this. The number of 'td' elements is unknown (the 'td' can be cloned an infinite number of times using a button, to submit multiple values). I added the alerts to the jQuery for testing purposes. When I added the jQuery code and hidden checkbox into my source code (I made it visible for testing purposes), the code wouldn't work AND all the other jQuery on my web page stopped working! jQuery code: ``` $(document).ready(function(){ /***post all 'required' checkboxes instead of just checked ones***/ $(".required").click(function(event){ event.preventDefault(); alert("test"); nextIndex = this.index() + 1; alert(nextIndex); $(".required:eq(nextIndex)").attr("checked", !.required:eq(nextIndex).attr("checked")); }); }); ``` HTML: ``` <td> <input type="checkbox" class="required" name="required[]" value="true"> <input type="checkbox" class="required" name="required[]" value="false" style="display: none;" checked> </td> ```

Original source