Search code examples
javascripthtmlformscheckboxselectors-api

javascript - prevent checkboxes from becoming both checked AND disabled


I have a program where javascript changes several checkboxes, making them, disabled, checked, or unchecked based on what other boxes are checked. I've noticed that if you have a checked checkbox and then you make it disabled, it can be both checked and disabled at the same time. I don't want this to ever be possible. I want any checkbox that becomes disabled, to also become unchecked. I was looking for an easy way to do it. I thought queryselectorall would work. Here's a simplified example. In this example, I made one of the boxes checked AND disabled by default. If you click another box, it should get rid of the check in the disabled box. I thought this simple function would do that, but it doesn't work.

 function fixit() {
    document.querySelectorAll('input[type="checkbox"]:checked:disabled').checked=0;
    }
    <form id='theform' name='mainform' method='post' action='#'>
    box1<input onClick='fixit()' type='checkbox' disabled checked> 
    box2<input onClick='fixit()' type='checkbox'>
    box3<input onClick='fixit()' type='checkbox'>
    </form>


Solution

  • querySelectorAll returns an element list, which does not have a property checked. You need to iterate over the list of elements and apply your change.

    function fixit() {
      var cbs = document.querySelectorAll('input[type="checkbox"]:checked:disabled');
      for(var i = 0;i<cbs.length;i++){
        cbs[i].checked = 0;
      }
    }
    <form id='theform' name='mainform' method='post' action='#'>
        box1<input onClick='fixit()' type='checkbox' disabled checked> 
        box2<input onClick='fixit()' type='checkbox'>
        box3<input onClick='fixit()' type='checkbox'>
        </form>