簡體   English   中英

選中復選框是否檢查其他具有相同值的復選框

[英]check checkbox if other checkbox with same value is checked jquery

如果選中了其他具有相同值的復選框,則如何選中該復選框。 如果選擇1,則應選中另一個具有相同值的div復選框。

 <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> 

變得如此簡單:

 $('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> 

如果您希望其他項目在取消選中時保持選中狀態,請查看Arun P Johny的解決方案

您可以使用屬性選擇器來獲取具有相同值的其他復選框,並在選中當前復選框的情況下設置其選中屬性

 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> 

您可以使用具有相同值的filter()復選框並設置其屬性。

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM