Dominykas V. Dominykas V. -4 years ago 74
HTML Question

check checkbox with the same value and then show div

I have a code where if you check checkbox with the same value other checkboxes with that value also checks, but I want that when it is checked also show div and if it's unchecked hide.

I tried this, but that don't work. Any help is welcome. Thank you!



$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked)) {
$(".div1").show();
} else {
$(".div1").hide();
}
});
});

.div1 {
display:none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input type="checkbox" value="one">1
<input type="checkbox" value="two">2
</div>
<div class="div1">
<p>This is text</p>
</div>
<div>
<input type="checkbox" value="one">1
<input type="checkbox" value="two">2
</div>
<div class="div1">
<p>This is another text</p>
</div>




Answer Source

$(document).ready(function() {
  $('input[type="checkbox"]').click(function() {
  $('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked)
    if ($(this).is(":checked")) {//change if condition
      $(".div1").show();
    } else {
      $(".div1").hide();
    }
  });
});
.div1 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
  <input type="checkbox" value="one">1
  <input type="checkbox" value="two">2
</div>
<div class="div1">
  <p>This is text</p>
</div>
<div>
  <input type="checkbox" value="one">1
  <input type="checkbox" value="two">2
</div>
<div class="div1">
  <p>This is another text</p>
</div>

  1. Change if condition because your condition $('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked) is not returning Boolean value it is setting the checkbox to checked or unchecked
  2. I would suggest to use change instead of click

$(document).ready(function() {
  $('input[type="checkbox"]').change(function() {//suggest to use change
  $('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked)
    if ($(this).is(":checked")) {//change if condition
      $(".div1").show();
    } else {
      $(".div1").hide();
    }
  });
});
.div1 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
  <input type="checkbox" value="one">1
  <input type="checkbox" value="two">2
</div>
<div class="div1">
  <p>This is text</p>
</div>
<div>
  <input type="checkbox" value="one">1
  <input type="checkbox" value="two">2
</div>
<div class="div1">
  <p>This is another text</p>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download