HTML: Checkbox default value

后端 未结 3 524
执念已碎
执念已碎 2021-01-01 10:38

When I submit a HTML form with a checked checkbox that doesn\'t have an explicitly defined value, Chrome sends on as a value for that field.

<
相关标签:
3条回答
  • 2021-01-01 10:59

    The HTML 4.01 specification does not specify the value of a checked checkbox. It just refers it saying that it is “on”, but this is just prose and does not say what the default value is. But it also says (under the description of the input element) that the value attribute is required in this case.

    So <input type=checkbox name=foo> has undefined behavior as regards to the value used, though in practice browsers use value=on as the default.

    0 讨论(0)
  • 2021-01-01 11:06

    HTML Living Standard reflects this: The value is in mode "default/on", that means it's value is "on" if no value attribute is provided. From 4.10.7.1.16 Checkbox state (type=checkbox) - HTML Living Standard (Sep 2013):

    • The value IDL attribute is in mode default/on.

    [...]

    default/on
    On getting, if the element has a value attribute, it must return that attribute's value; otherwise, it must return the string "on". On setting, it must set the element's value attribute to the new value.

    This is quite identically also part of another HTML specification, the W3C HTML 5 Aug 2013 Recommendation Specification has this as well:

    • http://www.w3.org/TR/html5/forms.html#checkbox-state-(type=checkbox)
    • http://www.w3.org/TR/html5/forms.html#dom-input-value-default-on

    For reference my earlier comment:

    Firefox (Sep 2013), Chrome (Sep 2013), Internet Explorer (6): "on". I suspect this goes back a long way. http://lxr.mozilla.org/classic/source/lib/layout/layform.c#86 - as most browsers need to have some default value for their own code objects I guess this "on" is just common.

    0 讨论(0)
  • 2021-01-01 11:09

    Browsers will send the value of a checkbox (in the POST data) only if it is checked. A check to see if a value (any value) for a particular checkbox is present in the POST data is all you need.

    i.e.

    // no need to check against 'on', 'true', '1' etc..
    if(post data contains a value for checkbox1) {
        // checkbox 1 is checked
    }
    else {
        // not checked
    }
    
    0 讨论(0)
提交回复
热议问题