Can HTML checkboxes be set to readonly?

前端 未结 30 1629
無奈伤痛
無奈伤痛 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:59

    an alternative idea is to use an overlay and cover up your readonly inputs

    http://pure-essence.net/2011/09/22/jquery-read-only-elements/

    0 讨论(0)
  • 2020-11-22 08:59

    If you want ALL your checkboxes to be "locked" so user can't change the "checked" state if "readonly" attibute is present, then you can use jQuery:

    $(':checkbox').click(function () {
        if (typeof ($(this).attr('readonly')) != "undefined") {
            return false;
        }
    });
    

    Cool thing about this code is that it allows you to change the "readonly" attribute all over your code without having to rebind every checkbox.

    It works for radio buttons as well.

    0 讨论(0)
  • 2020-11-22 09:00

    I would use the readonly attribute

    <input type="checkbox" readonly>
    

    Then use CSS to disable interactions:

    input[type='checkbox'][readonly]{
        pointer-events: none;
    }
    

    Note that using the pseudo-class :read-only doesn't work here.

    input[type='checkbox']:read-only{ /*not working*/
        pointer-events: none;
    }
    
    0 讨论(0)
  • 2020-11-22 09:01
    <input type="radio" name="alwaysOn" onchange="this.checked=true" checked="checked">
    <input type="radio" name="alwaysOff" onchange="this.checked=false" >
    
    0 讨论(0)
  • <input name="isActive" id="isActive" type="checkbox" value="1" checked="checked" onclick="return false"/>
    
    0 讨论(0)
  • 2020-11-22 09:02

    I know that "disabled" isn't an acceptable answer, since the op wants it to post. However, you're always going to have to validate values on the server side EVEN if you have the readonly option set. This is because you can't stop a malicious user from posting values using the readonly attribute.

    I suggest storing the original value (server side), and setting it to disabled. Then, when they submit the form, ignore any values posted and take the original values that you stored.

    It'll look and behave like it's a readonly value. And it handles (ignores) posts from malicious users. You're killing 2 birds with one stone.

    0 讨论(0)
提交回复
热议问题