Uncheck chain checkbox

2

I have a checkbox option that when active, shows a second check. I need to make sure the second checkbox is only active if the first one is. My function shows and hides the second check according to the value of the first one, but I need it also to clear the second one when the first one is cleared and this is not working. Can you help me ? Follow my code.

$("#ck1").click(function() {
  if ($("#ck1").is(':checked')) {
    $("#ck2").show();
  } else {
    if ($("#ck2").is(':checked')) {
      $("#ck2").prop('checked', false);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><inputtype="checkbox" id="ck1" name="ck1" />
  <label for="ck1">Check 1</label>
</div>

<div style="display: none;">
  <input type="checkbox" id="ck2" name="ck2" />
  <label for="ck2">Check 2</label>
</div>
    
asked by anonymous 25.10.2017 / 19:48

3 answers

1

To hide the second checkbox , you need to hide the div it is in:

$("#ck1").on("change",function(){
    if( $(this).is(':checked') )
        $("#ck2").prop('checked',true).parent().show();
    else {
        $("#ck2").prop('checked',false).parent().hide();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><inputtype="checkbox" id="ck1" name="ck1" />
  <label for="ck1">Check 1</label>
</div>

<div style="display: none;">
  <input type="checkbox" id="ck2" name="ck2" />
  <label for="ck2">Check 2</label>
</div>
    
25.10.2017 / 20:18
0

Your conditions are wrong, it may be something like:

$("#ck1").change(function(){ // pega o evento de mudanca
    if( $(this).is(':checked') ) // verifica se checkbox 1 esta marcado
        $("#ck2").show();
    else { // senao esconde e desmarca checkbox 2
        $("#ck2").prop('checked', false);
        $("#ck2").hide();
    }
}); 
    
25.10.2017 / 20:00
0

There are many ways to work with jquery done with class directly in the element, working on div you end up forgetting that the element is still set, but just do not forget this detail at the time of programming that everything will work normally.

$("#ck1").change(function(){
    if( $(this).is(':checked') ){
        $(".label-to").show();
        $("#ck2").prop('checked', false).show();
    }else {
    $(".label-to").hide();
        $("#ck2").prop('checked', false).hide();        
    }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><inputtype="checkbox" id="ck1" name="ck1" />
  <label for="ck1">Check 1</label>
</div>

<div >
  <input style="display: none;" class="label-to" type="checkbox" id="ck2" name="ck2" />
  <label style="display: none;" class="label-to" for="ck2">Check 2</label>
</div>
    
25.10.2017 / 20:22