skip to Main Content

I’m trying to create a few checkboxes that when checked, will check another… which I got to work! But, the problem I’m having now is that if multiple are selected and one is unchecked at any point, the additional checkbox get unchecked no matter what. I’d like to find a way to have the additional checkbox stay checked, as long as one of the others is, and uncheck if none are selected.

For example: I have 4 checkboxes, if a user selects #1 I want to check #2. Or if a user selects #1 + #3, check #2, but if #3 is unchecked, #2 stays as long as 1,3, or 4 are. I hope this makes sense. I’ve been trying different things, but this is the code where I landed. Any help, advice on a better way to accomplish this would be greatly appreciated.

var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");

chk1.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk3.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk4.on('change', function(){
  chk2.prop('checked',this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">4

2

Answers


  1. If you want to keep chk2 checked until all others are unchecked, you have to look for the status of all other boxes in each event handler. Ideally, you would create a function for that, so you don’t need to repeat your code for all handlers.

    function toggleChk2() {
      let check2 = (chk1.is(':checked') ||
          chk3.is(':checked') ||
          chk4.is(':checked'))
      chk2.prop('checked',check2);
    }
    
    chk1.on('change', function(){
      toggleChk2();
    });
    chk2.on('change', function(){
      toggleChk2();
    });
    chk3.on('change', function(){
      toggleChk2();
    });
    chk4.on('change', function(){
      toggleChk2();
    });
    

    You can also add this function to the change handler of chk2 if you want to prevent manual change of that checkbox.

    Login or Signup to reply.
  2. For the record: alternative without JQuery, using event delegation and a css selector to query the state of the other checkboxes:

    [`change`, `click`].forEach( evtType => 
      document.addEventListener(evtType, handle) );
    
    function handle(evt) {
      if (evt.target.closest(`.user_name`)) {
        const cb2 = document.querySelector(`.user_name[value="2"]`);
        const oneOfOthersChecked = 
          document.querySelector(`.user_name:not([value="2"]):is(:checked)`);
        return cb2.checked = !!oneOfOthersChecked || cb2.checked;
      }
      if (evt.target.id === "empty") {
        return document.querySelectorAll(`.user_name:checked`)
          .forEach(cb => cb.checked = !cb.checked);
      }
      return true;
    }
    <input type="checkbox" value="1" class="user_name">1
    <br>
    <input type="checkbox" value="2" class="user_name">2
    <br>
    <input type="checkbox" value="3" class="user_name">3
    <br>
    <input type="checkbox" value="4" class="user_name">4
    <br>
    <button id="empty">Uncheck all</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search