I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.

Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?

41 Answers 41


Add a hidden input for the checkbox with a different ID:

<input id='testName' type='checkbox' value='Yes' name='testName'>
<input id='testNameHidden' type='hidden' value='No' name='testName'>

Before submitting the form, disable the hidden input based on the checked condition:

if(document.getElementById("testName").checked) {
    document.getElementById('testNameHidden').disabled = true;
  • 53
    If you're going with a markup-based solution like this, it's probably better to put the hidden input first, per many the other answers. If you're using PHP, you can then do away with the javascript dependency, because only the last value gets used. – Ben Sep 13 '13 at 17:40
  • 12
    gamov, you are mistaken, labels are attached to inputs based on the id attribute, not the input name attribute – Justin Emery Jan 31 '14 at 12:02
  • 14
    Hard to believe authors designed it this way. Why not to send all input fields with some default value for those not checked :( It would be much clearer solution then having to implement some hidden fields "hack". It must have been clear that it is going to be needed and they had to see that in advance. – Srneczek Feb 6 '15 at 10:23
  • 29
    This feels so hacky. – EralpB May 22 '15 at 13:33
  • 50
    Am I the only one who thinks that the underlying design of the checkbox element is terrible? They're a binary control, they should send binary values. – alexw Apr 21 '16 at 16:53

The solution I liked the most so far is to put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.

  <input type='hidden' value='0' name='selfdestruct'>
  <input type='checkbox' value='1' name='selfdestruct'>
  • 3
    Now that I re-read the question it seems this wasn't really what you wanted. However I got to this question when I was trying to figure out this answer so maybe it could be useful to someone else. – Sam Jan 2 '10 at 20:40
  • 2
    .NET is different, instead see stackoverflow.com/questions/7600817/… – KCD Nov 19 '12 at 1:21
  • 111
    It should be noted that if you check the box, the browser will send both the hidden and checkbox values. This solution then relies on the server's handling of the post variable with these 2 values. If it only takes the last value (e.g. PHP), your code will work as expected. However, some servers handle this differently, Some pick the first value, while others place both values in a list/array. – Michael Ekoka Feb 7 '13 at 7:05
  • 1
    This answer is build on the assumption that you can relay on only one of two equal named inputs will be send to the server - I don't understand why this has received so many up-votes? – Muleskinner Apr 24 '14 at 17:20
  • 7
    @sam dont know where you got that idea from? When two or more controls are named the same then both will be send to the server on submit (for checkboxes however, only if checked) - how they are handled on the server depends on the server side implementation. If you dont believe me you can see for yourself by monitoring the traffic using a tool like fiddler. – Muleskinner Apr 25 '14 at 12:01

I solved it by using vanilla JavaScript:

<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">

Be careful not to have any spaces or linebreaks between this two input elements!

You can use this.previousSibling.previousSibling to get "upper" elements.

With PHP you can check the named hidden field for 0 (not set) or 1 (set).

  • Why can't you have spaces or line breaks between the two elements? – Michael Potter Dec 30 '15 at 18:13
  • @MichaelPotter: this.previousSibling will get whitespace as sibling, so it dont work. – Marcel Ennix Feb 1 '16 at 12:55
  • 4
    Oh this is PERFECT! It solves the problem of posting multiple fieldsets with duplicate named fields there in. None of the other solutions do. Using Marcel's method, your posted fields will have equal length arrays. So this scenario: <fieldset name='fs1'> <input type="text" name="somefield[]"> <input type="checkbox" name="live[]"> </fieldset> <fieldset name='fs2'> <input type="text" name="somefield[]"> <input type="checkbox" name="live[]"> </fieldset> * Assume there were new lines there. They don't seem to be working in mini-markup code blocks – Brian Layman Jan 16 '17 at 0:26
  • 1
    This should be the accepted answer. It works with arrays (ex/ name="soup[]") – jdavid05 May 14 '19 at 17:34
  • 2
    You can use previousElementSibling instead of previousSibling. It is supported nearly everywhere, and it ignores text nodes. – MarSoft Jun 26 '19 at 0:27

My personal favorite is to add a hidden field with the same name that will be used if the check-box is unchecked. But the solution is not as easy as it may seems.

If you add this code:


The browser will not really care about what you do here. The browser will send both parameters to the server, and the server has to decide what to do with them.

PHP for example takes the last value as the one to use (see: Authoritative position of duplicate HTTP GET query keys)

But other systems I worked with (based on Java) do it the way around - they offer you only the first value. .NET instead will give you an array with both elements instead

I'll try to test this with node.js, Python and Perl at sometime.

  • 2
    ruby and node.js will both take the last value of any duplicated form fields. Ruby on Rails' helper methods construct checkboxes in this fashion for this reason. – nzifnab May 15 '12 at 18:44
  • 7
    Just to round that up - this is based on an attack called HTTP Parameter Pollution and has been analyzed by OWASP: owasp.org/images/b/ba/AppsecEU09_CarettoniDiPaola_v0.8.pdf (page 9) where you can find a list of 20 systems systems and see how they handle that. – SimonSimCity Sep 5 '12 at 21:41
  • 1
    Java Servlets gives you all, as long as you call request.getParameterValues – mauhiz Sep 17 '14 at 3:33

A common technique around this is to carry a hidden variable along with each checkbox.

<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>

On the server side, we first detect list of hidden variables and for each of the hidden variable, we try to see if the corresponding checkbox entry is submitted in the form data or not.

The server side algorithm would probably look like:

for input in form data such that input.name endswith .hidden
  checkboxName = input.name.rstrip('.hidden')
  if chceckbName is not in form, user has unchecked this checkbox

The above doesn't exactly answer the question, but provides an alternate means of achieving similar functionality.


you don't need to create a hidden field for all checkboxes just copy my code. it will change the value of checkbox if not checked the value will assign 0 and if checkbox checked then assign value into 1


    var this_master = $(this);

        var checkbox_this = $(this);

        if( checkbox_this.is(":checked") == true ) {
        } else {
  • 1
    This solution works fine and more elegant than polluting Dom with hidden fields. – Prasad Paranjape Jul 21 '15 at 18:28
  • 7
    This causes the box to get checked temporarily while the form is submitted. This is confusing (at best) to the user. – Mark Fraser Aug 24 '15 at 0:55

You can do some Javascript in the form's submit event. That's all you can do though, there's no way to get browsers to do this by themselves. It also means your form will break for users without Javascript. Better is to know on the server which checkboxes there are, so you can deduce that those absent from the posted form values ($_POST in PHP) are unchecked.

    var target = $(this).parent().find('input[type=hidden]').val();
    if(target == 0)
        target = 1;
        target = 0;

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

If you leave out the name of the checkbox it doesn't get passed. Only the test_checkbox array.

  • Very great solution, but in my case the live() doesnt work, so I used on() method: $('input[type=checkbox]').on("change",function(){...}); – Massa Jul 31 '14 at 17:37
  • 4
    LIVE is obsolete. Do not use it on answers in the stackoverflow anymore. Amem. – Ismael Sep 15 '14 at 14:14

I would actually do the following.

Have my hidden input field with the same name with the checkbox input

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

and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.

  $posted = array_unique($_POST['checkbox_name']);
  foreach($posted as $value){
    print $value;

I got this from a post remove duplicate values from array

  • What is the purpose of the [] on the name field value? – Michael Potter Dec 30 '15 at 18:12
  • @MichaelPotter It is so when post is sent to PHP, it will read the name `checkbox_name[] – Twister1002 Jan 12 '16 at 22:47
  • @Twister1002, I think you described the purpose of the name attribute, not the purpose of adding [] on the name. I did a web search and it seems some people do this with the names: groupname[elementname] to group fields together, but I did not find an explanation for empty []. – Michael Potter Jan 13 '16 at 3:12
  • 1
    @MichaelPotter Sorry, I thought I had finished that statement. But apparently not. Let me redo that. When it is sent to php the PHP processor will read it as an array. So with each name checkbox_name[] each value will be entered into an array, which you can then pull. Ex: $_POST['checkbox_name'][0] and so on with the increment of how many fields had that same name. Another example is if you had three fields named field_name[] you can get the second value of field_name like $_POST['field_name'][1]. Its purpose can be amazing if you have several fields that are of the same name. – Twister1002 Jan 13 '16 at 3:16

"I've gone with the server approach. Seems to work fine - thanks. – reach4thelasers Dec 1 '09 at 15:19" I would like to recommend it from the owner. As quoted: javascript solution depends on how the server handler (I didn't check it)

such as

if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";

Most of the answers here require the use of JavaScript or duplicate input controls. Sometimes this needs to be handled entirely on the server-side.

I believe the (intended) key to solving this common problem is the form's submission input control.

To interpret and handle unchecked values for checkboxes successfully you need to have knowledge of the following:

  1. The names of the checkboxes
  2. The name of the form's submission input element

By checking whether the form was submitted (a value is assigned to the submission input element), any unchecked checkbox values can be assumed.

For example:

<form name="form" method="post">
  <input name="value1" type="checkbox" value="1">Checkbox One<br/>
  <input name="value2" type="checkbox" value="1" checked="checked">Checkbox Two<br/>
  <input name="value3" type="checkbox" value="1">Checkbox Three<br/>

When using PHP, it's fairly trivial to detect which checkboxes were ticked.


$checkboxNames = array('value1', 'value2', 'value3');

// Persisted (previous) checkbox state may be loaded 
// from storage, such as the user's session or a database.
$checkboxesThatAreChecked = array(); 

// Only process if the form was actually submitted.
// This provides an opportunity to update the user's 
// session data, or to persist the new state of the data.

    foreach ($checkboxNames as $checkboxName) {
        if (!empty($_POST[$checkboxName])) {
            $checkboxesThatAreChecked[] = $checkboxName;
    // The new state of the checkboxes can be persisted 
    // in session or database by inspecting the values 
    // in $checkboxesThatAreChecked.


Initial data could be loaded on each page load, but should be only modified if the form was submitted. Since the names of the checkboxes are known beforehand, they can be traversed and inspected individually, so that the the absence of their individual values indicates that they are not checked.


I've tried Sam's version first. Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.

I've worked out Shailesh's idea in PHP, it works for me. Here's my code:

/* Delete '.hidden' fields if the original is present, use '.hidden' value if not. */
foreach ($_POST['frmmain'] as $field_name => $value)
    // Only look at elements ending with '.hidden'
    if ( !substr($field_name, -strlen('.hidden')) ) {

    // get the name without '.hidden'
    $real_name = substr($key, strlen($field_name) - strlen('.hidden'));

    // Create a 'fake' original field with the value in '.hidden' if an original does not exist
    if ( !array_key_exists( $real_name, $POST_copy ) ) {
        $_POST[$real_name] = $value;

    // Delete the '.hidden' element

I also like the solution that you just post an extra input field, using JavaScript seems a little hacky to me.

Depending on what you use for you backend will depend on which input goes first.

For a server backend where the first occurrence is used (JSP) you should do the following.

  <input type="checkbox" value="1" name="checkbox_1"/>
  <input type="hidden" value="0" name="checkbox_1"/>

For a server backend where the last occurrence is used (PHP,Rails) you should do the following.


For a server backend where all occurrences are stored in a list data type ([],array). (Python / Zope)

You can post in which ever order you like, you just need to try to get the value from the input with the checkbox type attribute. So the first index of the list if the checkbox was before the hidden element and the last index if the checkbox was after the hidden element.

For a server backend where all occurrences are concatenated with a comma (ASP.NET / IIS) You will need to (split/explode) the string by using a comma as a delimiter to create a list data type. ([])

Now you can attempt to grab the first index of the list if the checkbox was before the hidden element and grab the last index if the checkbox was after the hidden element.

Backend parameter handling

image source


I use this block of jQuery, which will add a hidden input at submit-time to every unchecked checkbox. It will guarantee you always get a value submitted for every checkbox, every time, without cluttering up your markup and risking forgetting to do it on a checkbox you add later. It's also agnostic to whatever backend stack (PHP, Ruby, etc.) you're using.

// Add an event listener on #form's submit action...
    function() {

        // For each unchecked checkbox on the form...

            // Create a hidden field with the same name as the checkbox and a value of 0
            // You could just as easily use "off", "false", or whatever you want to get
            // when the checkbox is empty.
            function(index) {
                var input = $('<input />');
                input.attr('type', 'hidden');
                input.attr('name', $(this).attr("name")); // Same name as the checkbox
                input.attr('value', "0"); // or 'off', 'false', 'no', whatever

                // append it to the form the checkbox is in just as it's being submitted
                var form = $(this)[0].form;

            }   // end function inside each()
        );      // end each() argument list

        return true;    // Don't abort the form submit

    }   // end function inside submit()
);      // end submit() argument list

You can also intercept the form.submit event and reverse check before submit

    $('input[type=checkbox]').prop('checked', function(index, value){
        return !value;

I know this question is 3 years old but I found a solution that I think works pretty well.

You can do a check if the $_POST variable is assigned and save it in a variable.

$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';

the isset() function checks if the $_POST variable is assigned. By logic if it is not assigned then the checkbox is not checked.


I see this question is old and has so many answers, but I'll give my penny anyway. My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true

    var b = $("input:checkbox:not(:checked)");
    $(b).each(function () {
        $(this).val(0); //Set whatever value you need for 'not checked'
    return true;

this way you will have a $_POST array like this:

            [field1] => 1
            [field2] => 0
  • Not working at my side. Trying to do this but still not posting all the checkboxes. [code] $("#filter input").change(function(e) { console.log('sublmit'); var b = $("input:checkbox:not(:checked)"); $(b).each(function () { $(this).val(2); $(this).attr("checked", true); }); $("#filter").submit(); }); [/code] – lio Jan 17 '18 at 17:59
  • Did the trick for me. The only drawback - on form submit every checkbox became checked. This can be confusing to a user, but because the page is reloading after form submits, I think it's a minor issue. – Oksana Romaniv Mar 7 '18 at 7:53
  • As Oksana said, it check all of the checkboxes, including any required checkboxes the user did not select themselves allowing the form to be submitted without the user agreeing to some condition. – bskool Nov 22 '18 at 7:43
    $(this).find('input[type="checkbox"]').each( function () {
        var checkbox = $(this);
        if( checkbox.is(':checked')) {
        } else {
            checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
            checkbox.prop('disabled', true);
  • 1
    This worked for me. Instead of using .submit you would use .click. Then remove the bit that disables checkboxes. After that it works perfectly. – cgrouge Sep 1 '16 at 17:36
  • 1
    Best answer no need to add another hidden input for each one – Sky Aug 31 '17 at 19:13

What I did was a bit different. First I changed the values of all the unchecked checkboxes. To "0", then selected them all, so the value would be submitted.

function checkboxvalues(){
  $("#checkbox-container input:checkbox").each(function({ 

  • Answer is good, but i want to know is it different from @Rameez SOOMRO's answer? – Imran Qamer May 10 '16 at 12:41
  • Similar end result, only this way you don't change the value of the checked checkboxes. – Seborreia May 11 '16 at 15:14

I would prefer collate the $_POST

if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;

it minds, if the POST doesn't have have the 'checkboxname'value, it was unckecked so, asign a value.

you can create an array of your ckeckbox values and create a function that check if values exist, if doesn`t, it minds that are unchecked and you can asign a value


Example on Ajax actions is(':checked') used jQuery instead of .val();

            var params = {
                books: $('input#users').is(':checked'),
                news : $('input#news').is(':checked'),
                magazine : $('input#magazine').is(':checked')

params will get value in TRUE OR FALSE..


Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.

Since I store values 'Y' and 'N' in my database and represent them via checked and unchecked checkboxes on page, I added hidden field for each value (checkbox) with 'Y' and 'N' values then use checkboxes just for visual representation, and use simple JavaScript function check() to set value of if according to selection.

<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>

use one JavaScript onclick listener and call function check() for each checkboxe on my web page:

function check(me)

This way 'Y' or 'N' values are always sent to server side script, it knows what are fields that should be updated and there's no need for conversion of checbox "on" value into 'Y' or not received checkbox into 'N'.

NOTE: white space or new line is also a sibling so here I need .previousSibling.previousSibling.value. If there's no space between then only .previousSibling.value

You don't need to explicitly add onclick listener like before, you can use jQuery library to dynamically add click listener with function to change value to all checkboxes in your page:


The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.

In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.

     $checkboxValue = false;
} else {
     $checkboxValue = $_POST['checkbox1'];

But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.


This can solely be accomplished with some javascript, as unchecked checkboxes don't get transmitted. So you need javascript that e.g. behind the scenes adds hidden fields on unchecking a checkbox. Without javascript this could not be done.


There is a better workaround. First of all provide name attribute to only those checkboxes that are checked. Then on click submit, through a JavaScript function you check all unchecked boxes . So when you submit only those will be retrieved in form collection those who have name property.

  //removing name attribute from all checked checkboxes
                  var a = $('input:checkbox:checked');
                   $(a).each(function () {

   // checking all unchecked checkboxes
                   $(b).each(function () {

Advantage: No need to create extra hidden boxes,and manipulate them.


@cpburnz got it right but to much code, here is the same idea using less code:


// jQuery OnLoad
    // Listen to input type checkbox on change event

HTML (note the field name using an array name):

    <input type="hidden" name="field_name[34]" value="1"/>
    <input type="checkbox">
    <input type="hidden" name="field_name[35]" value="0"/>

And for PHP:

    <input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
    <input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>

jQuery version of @vishnu's answer.

    $('#testNameHidden').prop('disabled', true);

If you are using jQuery 1.5 or below please use the .attr() function instead of .prop()


This solution is inspired by @desw's one.

If your input names are in "form style", you will lose array index association with your chekbox values as soon as one chekbox is checked, incrementing this "dissociation" by one unit each time a chekbox is checked. This can be the case of a form for inserting something like employees composed by some fields, for instance:

<input type="text" name="employee[]" />
<input type="hidden" name="isSingle[] value="no" />
<input type="checkbox" name="isSingle[] value="yes" />

In case you insert three employees at once and the first and the second ones are single, you will end up with a 5-element isSingle array, so you won't be able to iterate at once through the three arrays in order to, for instance, insert employees in a database.

You can overcome this with some easy array postprocessing. I'm using PHP at the server side and I did this:

$j = 0;
$areSingles = $_POST['isSingle'];
foreach($areSingles as $isSingle){
$areSingles = array_values($areSingles);

So this solution is overkill for this question, but it helped me when I had the same checkbox that occurred many times for different rows in a table. I needed to know the row the checkbox represented and also know the state of the checkbox (checked/unchecked).

What I did was to take the name attribute off of my checkbox inputs, give them all the same class, and create a hidden input that would hold the JSON equivalent of the data.


 <table id="permissions-table">
	    <input type="checkbox" class="has-permission-cb" value="Jim">
	    <input type="checkbox" class="has-permission-cb" value="Bob">
	    <input type="checkbox" class="has-permission-cb" value="Suzy">
 <input type="hidden" id="has-permissions-values" name="has-permissions-values" value="">

Javascript to run on form submit

var perms = {};
  var userName = this.value;
  var val = ($(this).prop("checked")) ? 1 : 0
  perms[userName] = {"hasPermission" : val};

The json string will get passed with the form as $_POST["has-permissions-values"]. In PHP, decode the string into an array and you will have an associative array that has each row and the true/false value for each corresponding checkbox. It is then very easy to walk through and compare to current database values.


All answers are great, but if you have multiple checkboxes in a form with the same name and you want to post the status of each checkbox. Then i have solved this problem by placing a hidden field with the checkbox (name related to what i want).

<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />

then control the change status of checkbox by below jquery code:

$(documen).on("change", "input[type='checkbox']", function() {
    var checkbox_val = ( this.checked ) ? 1 : 0;

now on change of any checkbox, it will change the value of related hidden field. And on server you can look only to hidden fields instead of checkboxes.

Hope this will help someone have this type of problem. cheer :)
