简体   繁体   中英

How to make only one checkbox checked in multiple checkboxes based on specific parent in jquery

Here I have number of checkboxes whose structure are like parent and child.Here I can check only one checkbox based on parent,Suppose for Parent1 I checked Child11 again when I checked Child12 , Child11 should unchecked similar to radio button.

Again same thing should be happen for Parent2 ,but if I check/uncheck any child in Parent2 ,children's of parent1 should not disturbed.

Can anyone please help me,here is the code below

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="details">
<ul>
<li>Parent1</li>
<li>
<ul>
<li><input type="checkbox"><span>Child11</span></li>
<li><input type="checkbox"><span>Child12</span></li>
</ul>
</li>
</ul>

<ul>
<li>Parent2</li>
<li>
<ul>
<li><input type="checkbox"><span>Child21</span></li>
<li><input type="checkbox"><span>Child22</span></li>
<li><input type="checkbox"><span>Child23</span></li>
</ul>
</li>
</ul>
</div>

CSS

ul li{
  list-style-type:none;
  }

 $(".p1chb").change(function() { $(".p1chb").prop('checked',false); $(this).prop('checked',true); }); ///above for parent 1, below for parent 2. $(".p2chb").change(function() { $(".p2chb").prop('checked',false); $(this).prop('checked',true); }); 
 ul li{ list-style-type:none; } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <div class="details"> <ul> <li>Parent1</li> <li> <ul> <li><input type="checkbox" id="Child11" name="Parent1" value="Child11" class="p1chb" checked> <label for="Child11">Child11</li> <li><input type="checkbox" id="Child12" name="Parent1" value="Child12" class="p1chb" unchecked> <label for="Child12">Child12</label></li> </ul> </li> </ul> <ul> <li>Parent2</li> <li> <ul> <li><input type="checkbox" id="Child21" name="Parent2" value="Child21" class="p2chb" checked> <label for="Child21">Child21</label></li> <li><input type="checkbox" id="Child22" name="Parent2" value="Child22" class="p2chb" unchecked> <label for="Child21">Child22</label></li> <li><input type="checkbox" id="Child23" name="Parent2" value="Child23" class="p2chb" unchecked> <label for="Child23">Child23</label></li> </ul> </li> </ul> </div> <div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM