Can HTML checkboxes be set to readonly?

前端 未结 30 2072
無奈伤痛
無奈伤痛 2020-11-22 08:39

I thought they could be, but as I\'m not putting my money where my mouth was (so to speak) setting the readonly attribute doesn\'t actually seem to do anything.

I\'d

30条回答
  •  日久生厌
    2020-11-22 08:57

    Belated answer, but most answers seem to over complicate it.

    As I understand it, the OP was basically wanting:

    1. Readonly checkbox to show status.
    2. Value returned with form.

    It should be noted that:

    1. The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.
    2. Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.
    3. A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.
    4. The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.

    Therefore, since the readonly attribute does not work, the best solution, requiring no javascript, is:

    1. A disabled checkbox, with no name or value.
    2. If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.

    So for a checked checkbox:

    
    

    For an unchecked checkbox:

    The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:

    Status: Implemented

提交回复
热议问题