Can HTML checkboxes be set to readonly?

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

    No, input checkboxes can't be readonly.

    But you can make them readonly with javascript!

    Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.

    jQuery(document).on('click', function(e){
          // check for type, avoid selecting the element for performance
          if(e.target.type == 'checkbox') {
              var el = jQuery(e.target);
              if(el.prop('readonly')) {
                  // prevent it from changing state
                  e.preventDefault();
              }
          }
    });
    input[type=checkbox][readonly] {
        cursor: not-allowed;
    }
    
    

    You can add this script at any time after jQuery has loaded.

    It will work for dynamically added elements.

    It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.

    There are so many ifs to make it not affect the performance of the page.

提交回复
热议问题