Akash khan Akash khan - 1 month ago 12
jQuery Question

Only one checkbox selectble from each options group

Sorry for duplicate question. I found there are many questions about this topic but these are not helpful to me. I have several group of checkbox.

<div class="options">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
</div>

<div class="options">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
</div>

<div class="options">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
<input class="option" type="checkbox">
</div>
...
...


I want to only one checkbox can be selectable from each group. I have tried with jQuery but it work for every checkbox not for indivitual group of checkbox.

$('body').on('change','.option', function() {
$('.option').not(this).prop('checked', false);
});


Another try with this

$('body').on('change','.option', function() {
$(this).parent('.options').find('.option').prop('checked', false);
$(this).prop('checked', true);
});


But no one solve my purpose. Please help.

Answer

Use siblings() method to get all the sibling elements or you can use radio button with the same name.

 $('body').on('change', '.option', function() {
   $(this).siblings().prop('checked', false);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="options">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
</div>

<div class="options">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
</div>

<div class="options">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
  <input class="option" type="checkbox">
</div>