简体   繁体   中英

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> 

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 .

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM