You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现组内单个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:

  1. 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).
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:58:29