dimanche 5 février 2023

Jquery Checkbox Checked Show / Hide Div if two checkboxes is check or unchecked

I have this simple jquery code for checkbox that checks via attributes. I know that there are many similarities for this answered already but the idea here is different.

I want to show the A_B div element for the following condition:

#1: User checked checkbox A or B then shows the A_B div element

#2: If user unchecked A checkbox but checkbox B is still checked. Then A_B div element is still showing.

*Note: This can be reversal for the situation*

#3 If user uncheckeds both A or B checkbox. Then only A_B div element will hide.

Right now. When I uncheck A or B checkbox. The div element will hide, should not suppose to toggle. Is there anything here to improve. To achieve the following 3 conditions?

Any ideas / solutions would be a great help. Might be useful also to some users that encounters the same problem as mine. Thanks.

$('input[chck-type="a_b"]').click(function(){
    if (
    $(this).prop("checked") == true
  ) {
      $('.A_B').removeClass('hide');
  } else {
    $('.A_B').addClass('hide');
  }
});

$('input[chck-type="c"]').click(function(){
    if (
    $(this).prop("checked") == true
  ) {
      $('.C_Box').removeClass('hide');
  } else {
    $('.C_Box').addClass('hide');
  }
});
.hide {display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="checkbox" chck-type="a_b">A</p>
<p><input type="checkbox" chck-type="a_b">B</p>
<p><input type="checkbox" chck-type="c">C</p>


<div class='A_B hide'>
This box is for A or B.
</div>

<div class='C_Box hide'>
This box is for C.
</div>



Aucun commentaire:

Enregistrer un commentaire