Search code examples
javascriptjqueryhtmlcheckboxchecked

How to make a checkbox unchecked based on another checkbox selection?


I have 6 checkboxes in my application.

<input type="checkbox" name="vehicle" id="vehicle1" value="one">one<br>
<input type="checkbox" name="vehicle" id="vehicle2" value="two">two<br>
<input type="checkbox" name="vehicle" id="vehicle3 value="three">three<br>
<input type="checkbox" name="vehicle" id="vehicle4" value="four">four<br>
<input type="checkbox" name="vehicle" id="vehicle5" value="five">five<br>
<input type="checkbox" name="vehicle" id="all" value="all">all<br>

And I have this jquery function, which would disable every other checkbox if the "all" checkbox is clicked.

$("#all").change(function(){
    var $inputs = $('input:checkbox')

    if($(this).is(':checked')){
           $inputs.not(this).prop('disabled',true);
    } else {
       $inputs.prop('disabled',false);
    }
});

If I select a checkbox other than the "all" checkbox, I have this following code which would disable the "all" checkbox.

$("[type=checkbox]").click(function() {
    if((this.value == "one") || (this.value == "two") || (this.value == "three") || (this.value == "four") || (this.value == "five")){
        $( "#all" ).prop( 'disabled', true );
    }
    else{
        $( "#all" ).prop( 'disabled', false );
    }
});

My problem here is, if I try to uncheck a checkbox after selecting it, this "all" checkbox is still disabled. I want it to be enabled once any checkbox is unchecked. Can you guys please help me with this?


Solution

  • Without jQuery, in pure DOM with event delegation.

    var $$ = s => Array.from(document.querySelectorAll(s))
    var $ = s => document.querySelector(s)
    
    // listen to input event
    document.body.addEventListener('input', function(e) {
      var target = e.target;
      var all;
      // when input event
      switch (true) {
        // if all, then disable other inputs
        case target.matches('input[name="vehicle"][value="all"]'):
          $$('input[name="vehicle"]:not([value="all"])')
            .forEach(
              element => element.disabled = target.checked)
          return false
        case target.matches("input[name='vehicle']:not([value='all'])"):
          $('input[name="vehicle"][value="all"]').disabled =
            $('input[name="vehicle"]:checked');
          return false;
      }
    })
    <input type="checkbox" name="vehicle" id="vehicle1" value="one">one<br>
    <input type="checkbox" name="vehicle" id="vehicle2" value="two">two<br>
    <input type="checkbox" name="vehicle" id="vehicle3" value="three" />three<br>
    <input type="checkbox" name="vehicle" id="vehicle4" value="four ">four<br>
    <input type="checkbox" name="vehicle" id="vehicle5" value="five " />five<br>
    <input type="checkbox" name="vehicle" id="all" value="all" />all<br>