0

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>

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.