bimacknyas
bimacknyas

Reputation: 37

check checkbox if other checkbox with same value is checked jquery

How to check checkbox if other checkbox with same value is checked. If select 1 than it should check the other div checkbox with the same value.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2 
</div>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2 
</div>

Upvotes: 0

Views: 2577

Answers (3)

blex
blex

Reputation: 25634

As simple as it gets:

$('input:checkbox').on('change', function(){
    //if(this.checked)    // optional, depends on what you want
    $('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2 
</div>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2 
</div>

If you want the others to remain checked when you uncheck one, look at Arun P Johny's solution.

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You can filter() checkboxes with same value and set its property.

$(function() {
  var checkboxes = $(":checkbox").change(function() {
    var value = $(this).val();
    checkboxes.filter(function() {
      return value == $(this).val()
    }).not(this).prop('checked', this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2
</div>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2
</div>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use a attribute selector to get other checkboxes with the same value and set its checked property if the current checkbox is checked

jQuery(function($) {
  var $checks = $('input:checkbox').change(function() {
    if (this.checked) {
      $checks.filter('[value="' + this.value + '"]').not(this).prop('checked', this.checked);
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2
</div>
<div>
  <input type="checkbox" value="1">1
  <input type="checkbox" value="2">2
</div>

Upvotes: 1

Related Questions