如何实现组内单个Checkbox勾选时仅选中其余所有Checkbox
Solution for Gender Checkbox Group Behavior
Here's how you can implement the requested checkbox interactions using jQuery:
Key Behaviors Implemented:
- Checking "All Genders" automatically selects all sub-options, and prevents unchecking any sub-option while "All" is selected.
- Checking or unchecking any sub-option will uncheck the "All Genders" box (if it was selected).
Full Working Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="product" value="all" />All Genders <br /> <input type="checkbox" name="product" value="women" />Women <br /> <input type="checkbox" name="product" value="men" />Men<br /> <input type="checkbox" name="product" value="bi" />Bi<br /> <script> // Handle "All Genders" checkbox click $('input[name="product"][value="all"]').on('click', function() { if ($(this).is(':checked')) { // Check all sub-options when "All" is selected $('input[name="product"]').not('[value="all"]').prop('checked', true); } }); // Handle sub-option checkbox clicks $('input[name="product"]').not('[value="all"]').on('click', function() { const $allCheckbox = $('input[name="product"][value="all"]'); if ($allCheckbox.is(':checked')) { // Prevent unchecking sub-options while "All" is selected $(this).prop('checked', true); } else { // Uncheck "All" when any sub-option is interacted with $allCheckbox.prop('checked', false); } }); </script>
How It Works:
- All Genders Click: When the "All" box is checked, we use
prop('checked', true)to select all other checkboxes in the group. If you uncheck "All", sub-options remain as they are (and you can now modify them freely). - Sub-option Click: If "All" is currently checked, any attempt to uncheck a sub-option is reversed immediately. If "All" isn't checked, interacting with any sub-option ensures "All" stays unchecked.
内容的提问来源于stack exchange,提问作者Mona Coder
相关产品推荐
相关产品推荐

