Can HTML checkboxes be set to readonly?

前端 未结 30 2045
無奈伤痛
無奈伤痛 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 09:06

    Most of the current answers have one or more of these problems:

    1. Only check for mouse not keyboard.
    2. Check only on page load.
    3. Hook the ever-popular change or submit events which won't always work out if something else has them hooked.
    4. Require a hidden input or other special elements/attributes that you have to undo in order to re-enable the checkbox using javascript.

    The following is simple and has none of those problems.

    $('input[type="checkbox"]').on('click keyup keypress keydown', function (event) {
        if($(this).is('[readonly]')) { return false; }
    });
    

    If the checkbox is readonly, it won't change. If it's not, it will. It does use jquery, but you're probably using that already...

    It works.

提交回复
热议问题