226

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

And if no value data is supplied, is the default value always "on"?

Assuming the above is correct, is this consistent behaviour across all browsers?

0

13 Answers 13

231

Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.

The default value is always "on", this should be consistent across browsers.

This is covered in the W3C HTML 4 recommendation:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

4
  • 28
    Unfortunately that's painful thruth, only checked checkboxes are sent to server, not unchecked ones. If you know in advance what checkboxes are on page then it is not problem on server side script to manage them. The problem is when you do not know that in advance - dynamically created checkboxes on page depending on some business logic. Then you have to make tricks and use parallel hiden input fields for those checkboxes and fulfill them with JavaScript.
    – sbrbot
    Commented Jul 19, 2016 at 9:48
  • The key to creating a consistent validator with "allowed unsuccessful controls (i.e. type="checkbox") is to designate these form controls as transient. When they are not successful, dynamically alter your sanitizer and validator accordingly. Commented Jan 13, 2017 at 1:15
  • 6
    Workaround: use <select>with two options on and off :-)
    – andy
    Commented May 23, 2018 at 9:26
  • 3
    recommend use hidden input to carry the checkbox value.
    – Rach Chen
    Commented Aug 5, 2021 at 0:47
116

In HTML, each <input /> element is associated with a single (but not unique) name and value pair. This pair is sent in the subsequent request (in this case, a POST request body) only if the <input /> is "successful".

So if you have these inputs in your <form> DOM:

<input type="text"     name="one"   value="foo"                        />
<input type="text"     name="two"   value="bar"    disabled="disabled" />
<input type="text"     name="three" value="first"                      />
<input type="text"     name="three" value="second"                     />

<input type="checkbox" name="four"  value="baz"                        />
<input type="checkbox" name="five"  value="baz"    checked="checked"   />
<input type="checkbox" name="six"   value="qux"    checked="checked" disabled="disabled" />
<input type="checkbox" name=""      value="seven"  checked="checked"   />

<input type="radio"    name="eight" value="corge"                      />
<input type="radio"    name="eight" value="grault" checked="checked"   />
<input type="radio"    name="eight" value="garply"                     />

Will generate these name+value pairs which will be submitted to the server:

one=foo
three=first
three=second
five=baz
eight=grault

Notice that:

  • two and six were excluded because they had the disabled attribute set.
  • three was sent twice because it had two valid inputs with the same name.
  • four was not sent because it is a checkbox that was not checked
  • six was not sent despite being checked because the disabled attribute has a higher precedence.
  • seven does not have a name="" attribute sent, so it is not submitted.

With respect to your question: you can see that a checkbox that is not checked will therefore not have its name+value pair sent to the server - but other inputs that share the same name will be sent with it.

Frameworks like ASP.NET MVC work around this by (surreptitiously) pairing every checkbox input with a hidden input in the rendered HTML, like so:

@Html.CheckBoxFor( m => m.SomeBooleanProperty )

Renders:

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

If the user does not check the checkbox, then the following will be sent to the server:

SomeBooleanProperty=false

If the user does check the checkbox, then both will be sent:

SomeBooleanProperty=true
SomeBooleanProperty=false

But the server will ignore the =false version because it sees the =true version, and so if it does not see =true it can determine that the checkbox was rendered and that the user did not check it - as opposed to the SomeBooleanProperty inputs not being rendered at all.

7
  • Worth noting that if you have multiple fields, such as with the extra hidden textbox, then the backend will receive an array of values.
    – Salami
    Commented Mar 11, 2016 at 9:18
  • It only receives an array if you use [] at the end of the input name, the default behaviour is to only submit the last element with that name, so as long as the hidden input is before the checkbox, it will work.
    – beeglebug
    Commented Apr 13, 2016 at 15:31
  • By having two fields with the same name (hidden field + checkbox field), and checking the checkbox, the post value is a comma separated string of the values, ie. something like "0,1"
    – ʞᴉɯ
    Commented Oct 5, 2016 at 11:16
  • 1
    @beeglebug What you're describing is how PHP handles names and values, the [] suffix is not a part of the HTML specification and browsers do not treat it specially. Without the [] PHP will only allow access to a single value (the last value) instead of all values.
    – Dai
    Commented Jul 18, 2017 at 22:19
  • 1
    Using the hidden property before the checkbox is working for me in all browsers I have tested using GET and POST with PHP. When I placed it after the checkbox control it always rendered the result false. Commented Sep 7, 2019 at 12:41
19

If checkbox isn't checked then it doesn't contribute to the data sent on form submission.

HTML5 section 4.10.22.4 Constructing the form data set describes the way form data is constructed:

If any of the following conditions are met, then skip these substeps for this element: [...]

The field element is an input element whose type attribute is in the Checkbox state and whose checkedness is false.

and then the default valued on is specified if value is missing:

Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then run these further nested substeps:

If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".

Thus unchecked checkboxes are skipped during form data construction.

Similar behavior is required under HTML4. It's reasonable to expect this behavior from all compliant browsers.

0
12

Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs

JS:

var chk = $('input[type="checkbox"]');
    chk.each(function(){
        var v = $(this).attr('checked') == 'checked'?1:0;
        $(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
    });

chk.change(function(){ 
        var v = $(this).is(':checked')?1:0;
        $(this).next('input[type="hidden"]').val(v);
    });

HTML:

<label>Active</label><input rel="active" type="checkbox" />
11

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

Yes, because otherwise there'd be no solid way of determining if the checkbox was actually checked or not (if it changed the value, the case may exist when your desired value if it were checked would be the same as the one that it was swapped to).

And if no value data is supplied, is the default value always "on"?

Other answers confirm that "on" is the default. However, if you are not interested in the value, just use:

if (isset($_POST['the_checkbox'])){
    // name="the_checkbox" is checked
}
9

None of the above answers satisfied me. I found the best solution is to include a hidden input before each checkbox input with the same name.

<input type="hidden" name="foo[]" value="off"/>

<input type="checkbox" name="foo[]"/>

Then on the server side, using a little algorithm you can get something more like HTML should provide.

function checkboxHack(array $checkbox_input): array
{
    $foo = [];
    foreach($checkbox_input as $value) {
        if($value === 'on') {
            array_pop($foo);
        }
        $foo[] = $value;
    }
    return $foo;
}

This will be the raw input

array (
    0 => 'off',
    1 => 'on',
    2 => 'off',
    3 => 'off',
    4 => 'on',
    5 => 'off',
    6 => 'on',
),

And the function will return

array (
    0 => 'on',
    1 => 'off',
    2 => 'on',
    3 => 'on',
)  
0
8

input type="hidden" name="is_main" value="0"

input type="checkbox" name="is_main" value="1"

so you can control like this as I did in the application. if it checks then send value 1 otherwise 0

7

From HTML 4 spec, which should be consistent across almost all browsers:

http://www.w3.org/TR/html401/interact/forms.html#checkbox

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

Successful is defined as follows:

A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

2

I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.

First I put a hidden input box in line with my checkbox , i.e.

 <td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]"   class="chk_milestone" ></td>

Now if all the checkboxes are un-selected then values returned by the hidden field will all be off.

For example, here with five dynamically inserted checkboxes, the form POSTS the following values:

  'delete_milestone' => 
array (size=7)
  0 => string 'off' (length=3)
  1 => string 'off' (length=3)
  2 => string 'off' (length=3)
  3 => string 'on' (length=2)
  4 => string 'off' (length=3)
  5 => string 'on' (length=2)
  6 => string 'off' (length=3)

This shows that only the 3rd and 4th checkboxes are on or checked.

In essence the dummy or hidden input field just indicates that everything is off unless there is an "on" below the off index, which then gives you the index you need without a single line of client side code.

.

0

Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.

0

Having the same problem with unchecked checkboxes that will not be send on forms submit, I came out with a another solution than mirror the checkbox items.

Getting all unchecked checkboxes with

var checkboxQueryString;

$form.find ("input[type=\"checkbox\"]:not( \":checked\")" ).each(function( i, e ) {
  checkboxQueryString += "&" + $( e ).attr( "name" ) + "=N"
});
0

in your post

 'your_field': your_field.is(':checked'),
-3

I resolved the problem with this code:

HTML Form

<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>

and the javascript function by change the checkbox value form:

//change value of checkbox element
function changeValueCheckbox(element){
   if(element.checked){
    element.value='on';
  }else{
    element.value='off';
  }
}

and the server checked if the data post is "on" or "off". I used playframework java

        final Map<String, String[]> data = request().body().asFormUrlEncoded();

        if (data.get("is-business")[0].equals('on')) {
            login.setType(new MasterValue(Login.BUSINESS_TYPE));
        } else {
            login.setType(new MasterValue(Login.USER_TYPE));
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.