Reputation: 37
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
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
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
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